Backbone.js路由器初始化不';我不能马上跑
我的代码如下:Backbone.js路由器初始化不';我不能马上跑,backbone.js,backbone-routing,Backbone.js,Backbone Routing,我的代码如下: var AppRouter = Backbone.Router.extend({ _data: null, _length: 0, _index: null, _todos: null, _subtodolist: null, _subtodos: null, routes: { "*action": "index", "category/:name": "hashcategory"
var AppRouter = Backbone.Router.extend({
_data: null,
_length: 0,
_index: null,
_todos: null,
_subtodolist: null,
_subtodos: null,
routes: {
"*action": "index",
"category/:name": "hashcategory"
},
initialize: function(options){
var self = this;
if (this._index === null){
$.ajax({
url: 'data/todolist.json',
dataType: 'json',
data: {},
success: function(data) {
self._data = data;
self._todos = new TodosCollection(data);
self._index = new CategoriesView({collection: self._todos});
//self._index.render();
}
});
return this;
}
return this;
},
index: function(){
this._index.render();
},
....
但是当我开始时,firebug控制台面板总是告诉我这一点。_index在index
函数中为空。我必须使用$底部的self.\u index.render()
。ajax success
回调函数来进行主页呈现(上面已注释掉)。似乎index
函数在initialize
函数之前运行。这是怎么发生的?我该怎么解决
顺便说一句,在
路由中
,如果我使用”:“index”
,它将不起作用。我必须使用“*操作”:“索引”
。但我在其他地方了解到,默认url可能只是空字符串。为什么我不能在这里使用它?看起来发生这种情况是因为这个。索引只在ajax回调中设置。因为这是异步的,所以不能保证它会在索引事件处理程序触发之前执行
根据文档,初始加载时需要的模型
如果不可能,构造此代码的一种方法可能是在到达路由时获取数据,并将重置事件绑定到视图,例如
var CategoriesView = Backbone.View.extend({
initialize: function() {
this.collection.on("reset", this.render);
},
...
var AppRouter = Backbone.Router.extend({
_index: null,
_todos: null,
routes: {
"": "index",
"category/:name": "hashcategory"
},
initialize: function(options){
var self = this;
self._todos = new TodosCollection();
self._index = new CategoriesView({ collection: self._todos });
},
index: function(){
this._todos.fetch();
},
您还需要设置集合以构造适当的URL来请求
数据/todolist.json
实际上,这里的问题是初始化
在其内部的ajax调用解决之前返回
您可以在入口点中执行以下操作(通常是$.ready()
)
这将获取路由,然后使用它们初始化路由器,并启动
主干网。历史记录
。显然,您不需要在initialize中再次执行ajax调用,只需使用在选项中传递的数据。您的问题在于路由的顺序。按顺序评估路由,以便“*操作”始终匹配
尝试:
Thx伙计,它现在可以工作了。还有一个问题,
“category/:name”:“hashcategory”
路由似乎从未触发。我的html中有一个
链接,该链接具有'href='#/category/num1'
属性。但每次单击它,url都会更改,但不会发生其他任何事情。我在hashcategory
方法中有一个console.log('started')
,但它不打印任何内容。你知道为什么吗?在你的代码中,我认为self.\u todos=newtodoscollection(数据)代码>应该是self.\u todos=new TodosCollection()代码>,对吗?
var self = this,
p = $.ajax({
url: 'data/todolist.json',
dataType: 'json'
});
p.done(function (data) {
AppRouter = new Backbone.Router({data: data});
Backbone.history.start({ pushState: true });
});
routes: {
"category/:name": "hashcategory"
"*action": "index",
}