【问题标题】:Strange behaviour of this in backbone.js Controller这个在backbone.js 控制器中的奇怪行为
【发布时间】: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


【解决方案1】:

您必须将路由操作指定到主干路由而不是控制器。在路由器内部是您要初始化控制器和视图的地方。

此外,没有 Backbone.history.loadURL() 方法。我认为您应该改用 Backbone.history.start() ,然后在路由器实例中调用导航,例如router.navigate('状态或 URL');

var myApp = Backbone.Router.extend( {
    _index: null,

    routes: {
        "": "index"                   
    },

    initialize: function(options){
        //Initialize your app here
        this.myApp = new myApp();
        //Initialize your views here
        this.myAppViews = new myAppView(/* args */);

        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(); //Change this to Backbone.history.start();
        }

    },

    // Route actions
    index: function() {
        this._index.render();
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 2020-03-31
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多