I to try create my first javascript app with backbone.js
And I found strange behaviour, don’t understand difference between 2 piece of code
One works well and second seems not work.
That show alert on homepage and ‘#test’ url
var AppRouter = Backbone.Router.extend({
routes:{
"": 'index',
"test": 'test'
},
index: function(){
alert('index');
},
test: function(){
alert('test');
}
});
var app = new AppRouter();
Backbone.history.start();
And that not work, but Backbone.history.hanlers looks identical
var router = new Backbone.Router({
routes:{
"": 'index',
"test": 'test'
},
index: function(){
alert('index');
},
test: function(){
alert('test');
}
});
Backbone.history.start();
The difference between the two bits of code is that in the first one you are creating a new class called
AppRouterwhereas in the second one you are just creating a plainBackbone.Routerclass.I may be misunderstanding, but it seems you are saying that the first example works, and the second one doesn’t?
The reason the second example does not work is because Backbone.Router only accepts the
routeshash as an argument to it’s constructor. Theindexandtestfunctions you have passed are not created as functions on the object.If you want to pass the
routeshash to the constructor you still need to extend Backbone.Router with the actual routing functions. For example: