骨干这种混乱

egi*_*dra 5 javascript this backbone.js

我有以下代码:

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);
    }

});
Run Code Online (Sandbox Code Playgroud)

我的问题在于appendItem函数内部.当我thisappendItem函数内部使用时,我相信它认为指的thisthis.collection而不是GoalPanelView.我该如何获得this来引用GoalPanelView,而不是collection?我试图将另一个变量传递给appendItem保存内容的函数this.elem,但它似乎没有用.

有一件事是有效的,当我将appendItem函数移动到collection并更改初始化以绑定到this.collection.bind('add', appendItem);但我不想将这些view东西放入collection逻辑中.

Ben*_*Ben 6

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

this.collection.bind('add', this.appendItem, this);
Run Code Online (Sandbox Code Playgroud)

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

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

编辑2 骨干参考 - 事件/开启