骨干这种混乱

时间:2012-03-26 23:57:29

标签: javascript backbone.js this

我有以下代码:

var GoalPanelView = Backbone.View.extend({

    // Bind to the goal panel DOM element
    el: $("#sidebar-goals"),    

    // Initialize the collection
    initialize: function() {
        this.collection = Goals;
        this.collection.bind('add', this.appendItem);
    },

    // Create a new goal when a user presses enter in the enter goal input
    createOnEnter: function(e) {
        if (e.keyCode != 13) return;
        this.addItem();
        //Goals.create(this.newAttributes());           
    },

    // Add the goal item to the goal list
    addItem: function() {
        var goal = new Goal();
        goal.set(this.newAttributes());
        var goalsElem = this.el;
        this.collection.add(goal);
        $(this.el).children("#enter-goal").val('');
    },

    // Append DOM element to the parent el
    appendItem: function(item) {
        var goalView = new GoalView({
            model: item,
        });
        $(this.elem).append(goalView.render().el);
    }

});

我的问题出在appendItem函数内部。当我在this函数中使用appendItem时,我认为它认为this指的是this.collection而不是GoalPanelView。如何让this引用GoalPanelView而不是collection?我试图将另一个变量传递到appendItem函数中,该函数保存this.elem的内容,但它似乎不起作用。

有一件事是我将appendItem函数移动到collection并将初始化更改为绑定到this.collection.bind('add', appendItem);,但我不想放view填入collection逻辑。

3 个答案:

答案 0 :(得分:6)

您可以在绑定事件处理程序时添加范围,如下所示:

this.collection.bind('add', this.appendItem, this);

范围在处理程序中设置this的值。在你的情况下,当前对象。

编辑: Javascript Garden有一个很好的解释,为什么this.appendItem实际上不包含函数本身的范围,它只是一个函数指针,而不是方法指针。 Javascript的一个怪癖..

修改2 Backbone Reference - Events / on

答案 1 :(得分:2)

要更新(从Backbone 0.9.2开始),正确的方法是:

initialize: function() {
    this.collection.on("add", this.appendItem, this);
    ...
}


根据您的使用情况,您可能还需要考虑:

initialize: function() {
    this.listenTo(this.collection, "add", this.appendItem);
    ...
}

答案 2 :(得分:0)

您还可以在_.bindAll方法中使用下划线的initialize功能:

initialize: function() {
   _.bindAll(this);
   this.collection = Goals;
   this.collection.bind('add', this.appendItem);
}

现在对GoalPanelView上的任何方法(例如appendItem)的任何调用都将作为范围,以便对this的引用引用GoalPanelView实例。

如果您不希望范围GoalPanelView

的所有方法,也可以将方法名称列表作为字符串传递

见这里:http://underscorejs.org/#bindAll

相关问题