I have a Backbone.Marionette app configured using the AppRouter as well as the EventAggregator.
The initializer starts the router, and then history. I know for sure that my EventAggregator is set up properly - MyVent.trigger('abc') works properly in the console. The AppRouter also seems to be working properly as navigating to an undefined URL results in a 404, as expected.
Am I missing something?
//Initializer
MyApp.addInitializer(function(options){
//do stuff here
router = new MyRouter(MyController);
console.log('routing started!');
MyVent.trigger('routing:started'); <-- this works
});
//EventAggregator
MyVent = new Backbone.Marionette.EventAggregator();
MyVent.on('contactUs', function(){
console.log('ContactUs received by MyVent!');
startContactUsModal();
Backbone.history.navigate("contactus/");
});
MyVent.on('bookNow', function(){
console.log('BookNow received by MyVent!');
startBookNowModal();
Backbone.history.navigate("booknow/");
});
MyVent.on('home', function(){
console.log('home received by MyVent!');
startHome();
console.log('after starthome on myvent');
});
MyVent.on('routing:started', function(){
console.log('routing:started recieved at MyVent!');
if( ! Backbone.History.started) Backbone.history.start();
console.log('Backbone.history sucessfully started!');
});
//Controller
MyController = {
homeMethods:function(){
console.log('home receieved at mycontroller');
MyVent.trigger('home')
},
booknowMethods:function(){
MyVent.trigger('bookNow')
},
contactusMethods:function(){
MyVent.trigger('contactUs')
}
};
//Router
MyRouter = Backbone.Marionette.AppRouter.extend({
controller: MyController,
routes: {
'' : 'homeMethods',
'tours' : 'toursMethods',
'booknow' : 'booknowMethods',
'contactus' : 'contactusMethods'
},
});
WOW! What a stupid mistake - at least I'm getting faster at identifying these.
Declaring routes in AppRouter, is different than in the Backbone router.
Marionette: appRoutes
Regular Backbone: routes
Related
I have main app with subapps:
main_app
|-mainRouter.js
|-sub_app
|-subAppRouter.js
subAppRouter.js extends mainRouter.js. subAppRouter.js has handler for route (e.g. /app1/item/). I have no access to subAppRouter.
Here is what I need:
In mainRouter I want to create routing that will handle all URL's from all apps.
It should handle route , make some check and in one case it should continue firing handler from subAppRouter for that url, else it should make redirect (e.g. /app2/somepage).
Could someone helps me with finding the best solution how to do it?
In other words: how to realize interceptor pattern via router in backbone?
Thanks
i will rephrase your question in points
1- you have a main router for common routes
2- you have a specialized router for some app routes
3- you need your main router to choose weather to handle the route of just forward it to sub router
to achieve this i suggest the following
1- create the main router , extending Backbone.Router
var mainRouter = Backbone.Router.extend({
routes:{
'index':'loadIndex',
//other common app routes......
},
loadIndex: function(){
//code to load index
}
});
2- then define the sub router for app,extending the main router, but notice how routes is defined
var subAppRouter = mainRouter.extend({
initialize: function(){
// here we will extend the base routes to not lose default routing, and add app special routing
_.extend(this.routes, {
'subApp/index': 'subAppIndex'
});
},
subAppIndex: function(){
// code to load sub app index
},
});
then you can use the sub router which will contains the base routing also
Here is a good article about subrouting. This works perfect for me.
Include subroute js lib in your project:
<script type="text/javascript" src="backbone.subroute.min.js"></script>
HTML body example:
App1
App2
<div class="app">
</div>
JS Code example:
var MyApp = {};
MyApp.App1 = {
Router: Backbone.SubRoute.extend({
routes: {
"": "init",
"sub1": "sub1"
},
init: function () {
console.log("app1");
$(".app").html($("<h1 />", {text: "App1"}));
$(".app").append($("<a/>", {href: "#app1/sub1", text: "sub1"}));
},
sub1: function () {
console.log("sub1");
$(".app").append($("<h2 />", {text: "sub1"}));
}
})
};
MyApp.Router = Backbone.Router.extend({
initialize: function () {
if(!MyApp.Routers){
MyApp.Routers = {};
}
},
routes: {
"app1/*subroute": "invokeApp1Router",
"app2": "app2"
},
invokeApp1Router: function (subroute) {
if(!MyApp.Routers.App1){
MyApp.Routers.App1 = new MyApp.App1.Router("app1/");
}
},
app2: function () {
console.log("app2");
$(".app").html($("<h1 />", {text: "App2"}));
}
});
$(document).ready(function () {
new MyApp.Router();
Backbone.history.start();
})
Just want to get some basic routing up and going. Having seen a number of examples I thought the code below should work, but when I run I get the error "Unable to get property 'doChat' of undefined or null reference". Do I have the initialization sequence wrong?
require(["marionette", "jquery.bootstrap", "jqueryui"], function (Marionette) {
window.App = new Marionette.Application();
App.start();
App.addRegions({
//add some regions here
});
//Set up routing
var AppRouter = Marionette.AppRouter.extend({
appRoutes: {
"": "doDefault",
"chat": "doChat"
},
doDefault: function () {
alert("doing default...")
},
doChat: function () {
alert("doing chat...")
}
});
var router = new AppRouter();
//History
if (Backbone.history) {
Backbone.history.start();
}
})
The AppRouter allows two types of routes, standard backbone routes as defined in the routes property and routes which call functions in another object defined in the appRoutes property.
So to get you above code working, you can do one of two things. The quickest is simply to change the appRoutes property to routes which will do normal backbone routing. The second option is to create another object and pass that to the AppRouter as the controller during instantiation:
var myController = {
doDefault: function () {
alert("doing default...")
},
doChat: function () {
alert("doing chat...")
}
}
var router = new AppRouter({
controller: myController
});
This is detailed in the AppRouter documentation.
Iv'e set up my first little backbone app with a router to see if i can get some actions firing. I can't. I don't get an error message, but the console.log messages aren't displaying. Is there something more I have to set up to get the app started?
window.BreakfastApp = new (Backbone.Router.extend({
routes: { "": "interest", "products/:type": "products"},
initialize: function(){
console.log("hello world");
},
start: function(){
Backbone.history.start({pushState: true});
},
interest: function(){
console.log('interest')
},
products: function(type){
console.log('product' + type )
},
toppings: function(){
console.log('toppings')
},
results: function(){
console.log('results')
}
}));
$(function(){
BreakfastApp.start();
});
The documentation says:
During page load, after your application has finished creating all of
its routers, be sure to call Backbone.history.start(), or
Backbone.history.start({pushState: true}) to route the initial URL.
In your case something like:
var BreakfastAppRouter = Backbone.Router.extend({
...
});
var router = new BreakfastAppRouter();
Backbone.history.start();
should do the job.
In my backbone function, i am navigating a id to routers, but the function not calling... as well i have given the different sample navigate urls to my links, those are not calling the functions..
mycode :
(function($){
var myRouter = Backbone.Router.extend({
routes:{
"":"defaultRoute", //onload it works
'#/name/:id':"nameData",
// i am calling this function on default Router
'#/project/:id':"projectData"
},
defaultRoute:function(){
console.log('default')
startRoute.navigate("#/name/3"); // i am redirecting
},
nameData:function(id){
console.log(id); // id not consoling not called this func.
},
projectData:function(project){
console.log(project);
}
});
var startRoute = new myRouter();
Backbone.history.start();
})(jQuery);
my url : http://localhost:85/router/web/#/name/3
my html :
<ul class="name">
<li>name1</li>
<li>name2</li>
<li>name3</li>
<li>name4</li>
<li>name5</li>
</ul>
any one find me the wrong this what i do here.. please
All my functions are correct, by mistrake i added the hash on the routes prams.
update function here:
(function($){
var myRouter = Backbone.Router.extend({
routes:{
"":"defaultRoute",
'name/:id':"nameData",
'product/:id':"projectData"
},
defaultRoute:function(){
console.log('i am default');
},
nameData:function(e,id){
console.log(id);
},
projectData:function(project){
console.log(project);
}
});
var startRoute = new myRouter();
Backbone.history.start();
})(jQuery);
I'm a backbone newbie, so I'm sort of fumbling on getting an app set up. I'm using the backbone-boilerplate (https://github.com/tbranyen/backbone-boilerplate) and github-viewer (https://github.com/tbranyen/github-viewer) as a reference, though when running I seem to be getting a "this.model is undefined".
Here is my current router.js:
define([
// Application.
"app",
//Modules
"modules/homepage"
],
function (app, Homepage) {
"use strict";
// Defining the application router, you can attach sub routers here.
var Router = Backbone.Router.extend({
initialize: function(){
var collections = {
homepage: new Homepage.Collection()
};
_.extend(this, collections);
app.useLayout("main-frame").setViews({
".homepage": new Homepage.Views.Index(collections)
}).render();
},
routes:{
"":"index"
},
index: function () {
this.reset();
this.homepage.fetch();
},
// Shortcut for building a url.
go: function() {
return this.navigate(_.toArray(arguments).join("/"), true);
},
reset: function() {
// Reset collections to initial state.
if (this.homepage.length) {
this.homepage.reset();
}
// Reset active model.
app.active = false;
}
});
return Router;
}
);
And my homepage.js module:
define([
"app"
],
function(app){
"use strict";
var Homepage = app.module();
Homepage.Model = Backbone.Model.extend({
defaults: function(){
return {
homepage: {}
};
}
});
Homepage.Collection = Backbone.Collection.extend({
model: Homepage.Model,
cache: true,
url: '/app/json/test.json',
initialize: function(models, options){
if (options) {
this.homepage = options.homepage;
}
}
});
Homepage.Views.Index = Backbone.View.extend({
template: "homepage",
el: '#mainContent',
render: function(){
var tmpl = _.template(this.template);
$(this.el).html(tmpl(this.model.toJSON()));
return this;
},
initialize: function(){
this.listenTo(this.options.homepage, {
"reset": function(){
this.render();
},
"fetch": function() {
$(this.el).html("Loading...");
}
});
}
});
return Homepage;
});
Thanks in advance for the help!
Update: After much googling (you should see how many tabs I have open), I think I made a little bit of headway, but still no luck. I updated my router to have the following:
app.useLayout("main-frame").setViews({
".homepage": new Homepage.Views.Index()
}).render();
I made a number of modifications to my homepage.js module to now look like this:
define([
"app",
["localStorage"]
],
function(app){
"use strict";
var Homepage = app.module();
Homepage.Model = Backbone.Model.extend({
defaults: function(){
return {
homepage: {}
};
}
});
Homepage.Collection = Backbone.Collection.extend({
//localStorage: new Backbone.LocalStorage("Homepage.Collection"),
refreshFromServer: function() {
return Backbone.ajaxSync('read', this).done( function(data){
console.log(data);
//save the data somehow?
});
},
model: Homepage.Model,
cache: true,
url: '/app/json/test.json',
initialize: function(options){
if (options) {
this.homepage = options.homepage;
}else{
//this.refreshFromServer();
}
}
});
Homepage.Views.Index = Backbone.View.extend({
template: "homepage",
el: '#mainContent',
initialize: function(){
var self = this;
this.collection = new Homepage.Collection();
this.collection.fetch().done( function(){
self.render();
});
},
render: function(){
var data = this.collection;
if (typeof(data) === "undefined") {
$(this.el).html("Loading...");
} else {
$(this.el).html(_.template(this.template, data.toJSON()));
}
return this;
}
});
return Homepage;
});
As you can see, I have localStorage code but commented out for now because I just want to get everything working first. The ultimate goal is to have an initial call that loads data from a JSON file, then continues afterwards using localStorage. The app will later submit data after the user does a number of interactions with my app.
I am getting the main view to load, though the homepage module isn't populating the #mainContent container in the main view.
I did all of the googling that I could but frustrated that it's just not sinking in for me. Thanks again for looking at this and any feedback is appreciated!
I think your class hierarchy is a bit wonky here. Your instance of Homepage.Collection is actually assigning a homepage property out of options, for instance. Then you pass an instance of Homepage.Collection into Homepage.Views.Index as the homepage option... It's a bit hard to follow.
That said, it seems to me your problem is simply that you aren't supply a model option when you construct your Homepage.Views.Index:
new Homepage.Views.Index(collections)
collections doesn't have a model property, and thus I don't see how this.model.toJSON() later on in the view can have a model to access. Basically, you seem to want Homepage.Views.Index to handle a collection of models, not just one. So you probably need a loop in your render function that goes over this.collection (and you should change your construction of the view to have a collection option instead of homepage option).
If I'm missing something here or I'm unclear it's because of this data model oddness I mentioned earlier. Feel free to clarify how you've got it reasoned out and we can try again :)
This example code you have is a little bit confusing to me, but I think the problem lies in the following two lines of code:
".homepage": new Homepage.Views.Index(collections)
$(this.el).html(tmpl(this.model.toJSON()));
It looks like you pass a collection to the view, but in the view you use this.model, hence the error "this.model is undefined", since it is indeed undefined.
If you aren't in any rush, may I suggest that you start over. It seems you are trying too much too quickly. I see that you have backbone, requirejs (or some other module loader), and the boilerplate, which is a lot to take in for someone new to backbone. Trust me, I know, because I am relatively new, too. Maybe start with some hello world stuff and slowly work your way up. Otherwise, hacking your way through bits of code from various projects can get confusing.