0

是的,我是 JS 的新手,也是backbonejs 的新手。

现在让我们深入研究这个问题。

我在backbonejs Controller中有一个非常奇怪的行为。

这是我的控制器的代码

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方法的调用者函数正在改变它的范围。我需要保留它的范围。

4

1 回答 1

0

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

此外,没有方法 Backbone.history.loadURL()。我认为您应该改用 Backbone.history.start() 然后在路由器实例中调用导航,例如 router.navigate('state or 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();
    }
});
于 2013-03-31T17:59:57.503 回答