I'm trying to create my first BB app. It's going ok but I have a problem. My router looks like this:
var PlayersAppRouter = Backbone.Router.extend({
routes: {
'': 'index',
},
initialize: function () {
this.model = new PlayersAppModel({});
this.view = new PlayersAppView({model: this.model});
},
index: function () {
alert('It works'); //<-- It doesn't
},
});
And later in my code I have:
$(function () {
window.app = new PlayersAppRouter;
Backbone.history.start({pushState: true});
app开发者_如何转开发.model.players.reset(<?php require('players.php'); ?>); //<-- players.php loads a bunch of JSON data.
});
Now, why doesn't the index action of the router fire? Am I doing something wrong? Are there any other problems with this code?
The full app can be found here: http://development.zeta-two.com/development/f14/
Get rid of your pushState:true at it works
http://fiddle.jshell.net/r5TEk/9/show/
There maybe a bug with pushSate. See here
https://github.com/documentcloud/backbone/issues/451
Using a regular expression, add a route manually in the initialize
function.
...
initialize: function() {
this.route(/\/?/, 'index', this.index);
},
index: function() {
alert('It works!');
},
...
This works fine with {pushState: true}
.
http://jsfiddle.net/sergio/WpKPP/
http://jsfiddle.net/sergio/WpKPP/show
Can't remember where I read it, buy I find you have to call initialize
on the router. This is my working example, fired inside a jquery.ready
function.
MainView = new View.main();
appRouter = new Router();
// set up single page app with push state
Backbone.history.start({pushState: true});
appRouter.initialize();
Routes config.
routes: {
"": "index"
}
Using @serg.io answer this.route(/\/?/, 'index', this.index);
caused it override my other routes.
精彩评论