我有以下代码:骨干这种混乱
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
函数内。当我在appendItem
函数中使用this
时,我认为它认为this
是指this.collection
而不是GoalPanelView
。我如何获得this
来引用GoalPanelView
而不是collection
?我尝试将另一个变量传入appendItem
函数,该函数保存this.elem
的内容,但它似乎不起作用。该工作
的一件事是,当我提出的appendItem
功能为collection
,改变了初始化绑定到this.collection.bind('add', appendItem);
,但我不想把view
东西到collection
逻辑。
另一种方法是将'_.bindAll(this)'放入您的初始化函数中。这可以确保在对象中调用的任何函数都将与“this”的值一起适用于对象本身。如果你正在写很多回调,这很有用。 – rybosome 2012-07-30 06:02:32