Reputation: 11653
I have a pretty basic Backbone app which uses a router to instantiate views and collections. In playing around with the app, I noticed that if I put the line of code instantiating the router
router = new DocsRouter();
at the top of the application.js file, then the app didn't work; it had to be at the bottom of the file. Yet, this didn't make sense to me. Why should the location of this line of code matter, since everything important to start the app happens inside the router? Shouldn't I be able to trigger the router from anywhere?
window.DocsRouter = Backbone.Router.extend({
initialize : function() {
this.docs = new Docs();
this.docs.fetch();
this.docFormView = new DocFormView({ collection : this.docs });
this.docsView = new DocsCollectionViewTempo({ collection : this.docs });
this.docsView.render();
this.route("doc/:id", "doc", function(id){
console.log(id, this.docs.get(id).toJSON());
});
},
routes : {
"" : "root",
"about" : "about",
"doc/:id" : "doc"
},
root : function() { console.log('Vous êtes à la racine');},
about : function() { console.log('A propos : ceci est un tutorial BackBone');},
doc : function(id) { console.log(id, this.docs.get(id).toJSON()); }
});
router = new DocsRouter();
Backbone.history.start();
Upvotes: 0
Views: 68
Reputation: 2978
No. You cannot create an instance of DocRouter before DocRouter has been declared.
window.DocsRouter = Backbone.Router.extend({..});
router = new DocsRouter();
The order of these two lines has to be this. Before the first line DocRouter does not exists thus you can not instantiate it.
Upvotes: 1