【发布时间】:2013-03-31 17:32:34
【问题描述】:
是的,我是 JS 新手,也是backbonejs 的新手。
现在让我们深入研究这个问题。
我在backbonejs Controller 中有一个非常奇怪的this 行为。
这是我的控制器的代码
var controller = Backbone.Controller.extend( {
_index: null,
routes: {
"": "index"
},
initialize: function(options){
var self = this;
if (this._index === null){
$.getJSON('data/album1.json',function(data) {
//this line is working self._index is being set
self._index = new sphinx.views.IndexView({model: self._photos});
});
Backbone.history.loadUrl();
}
},
index: function() {
//this line is not working
//here THIS is pointing to a different object
//rather than it was available through THIS in initialize method
this._index.render();
}
});
这是文件末尾用于启动控制器的行。
removeFallbacks();
gallery = new controller;
Backbone.history.start();
现在,我错过了一些东西。但是什么??? 如果这是错误的方式,那么正确的方式是什么? 我需要从 index 方法访问我从 initialize 方法设置的属性。
看起来 index 方法的调用函数正在改变它的作用域。 我需要保留它的范围。
【问题讨论】:
-
@muistooshort 其实我正在关注Jquerys best friends 教程。
-
我推荐一个更新的教程,Backbone 从 0.5 版开始就没有
Backbone.Controller了,早在 2011 年 7 月就出现了。有很多小(而且不是那么小) ) 从 0.5 开始发生变化,所以学习这么旧的版本只会妨碍你。此外,jQuery 的模板系统已被弃用,不再受支持。
标签: backbone.js backbone-routing