0

I'm trying to create a master view/controller for a Backbone project, and I'm having troubles accessing the views within the view properly. Here's the code:

var Controller = Backbone.View.extend({
    initialize: function() {
        this.characterView = new CharacterView({model: character});
        this.encounterView = new EncounterView({collection: encounter});
        this.characterView.$el.on('click', '.attack', this.charAttack);
    },
    charAttack: function() {
        console.log(this.characterView);
    },
    render: function() {
        this.encounterView.render();
        this.characterView.render();
        console.log(this.characterView.model.toJSON());
    }
});

var controller = new Controller();
controller.render();

The this.characterView in charAttack is undefined whereas in the render function, it uses the right object. I'm not sure why render can access this.characterView, but charAttack can't. Any help to understand this would be greatly appreciated.

4

3 回答 3

1

_.bindAll添加到您的初始化函数中:

initialize: function() {
    _.bindAll(this); // assuming Underscore < 1.5.0
    this.characterView = new CharacterView({model: character});
    this.encounterView = new EncounterView({collection: encounter});
    this.characterView.$el.on('click', '.attack', this.charAttack);
},

这确保this了视图内部的函数(包括charAttack)始终引用视图。


要验证您是否遇到此问题,请在打开控制台的 Chrome 中尝试此操作:

charAttack: function() {
    debugger;
    console.log(this.characterView);
},

然后在控制台中输入 this 并查看它是否绑定到window或另一个变量。

于 2013-09-25T16:03:29.080 回答
0
于 2013-09-25T16:10:09.667 回答
0

this除非您已实例化您的对象,否则您无法访问元素。

var ModController = function(){
    var characterView;
    var encounterView;

    var Controller = Backbone.View.extend({
        initialize: function() {
            characterView = new CharacterView({model: character});
            encounterView = new EncounterView({collection: encounter});
            this.characterView.$el.on('click', '.attack', this.charAttack);
        },
        charAttack: function() {
            console.log(characterView);
        },
        render: function() {
            encounterView.render();
            characterView.render();
            console.log(this.characterView.model.toJSON());
        } 
    });

    return new Controller();

}

var myController = new ModController(); 
myController.render();

所以我相信Revealing Pattern可以解决你的问题。

于 2013-09-25T16:03:55.463 回答