cha*_*oor 3 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"
},
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();
},
....
Run Code Online (Sandbox Code Playgroud)
但是当我开始使用时,firebug控制台面板总是告诉我函数中this._index是null index.我必须self._index.render()在$.ajax success回调函数的底部使用以进行主页渲染(上面已注释掉).似乎index函数在initialize函数之前运行.怎么会发生这种情况,我该如何解决?
顺便说一句,routes如果我使用"": "index"它,它将无法正常工作.我必须使用"*action": "index".但我已经在其他地方学到了默认网址可能只是空字符串.为什么我不能在这里使用它?
事实上,这里的问题是initialize在其内部的ajax调用已经解决之前返回.
您可以做的是在您的切入点(通常$.ready())执行以下操作
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 });
});
Run Code Online (Sandbox Code Playgroud)
这将获取路由,然后使用它们初始化路由器并启动Backbone.history.显然你不需要在初始化时再次执行ajax调用,只需使用选项中传递的数据.