は、私は、次のコードを持っている:バックボーンこの混乱
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.collection
を指していると思います。 this
にcollection
ではなくGoalPanelView
を参照させるにはどうすればよいですか? this.elem
の内容を保持していたappendItem
関数に別の変数を渡そうとしましたが、うまくいかなかったようです。私はcollection
にappendItem
機能を移動し、this.collection.bind('add', appendItem);
にバインドするために初期化を変更したときに働い
一つのことでしたが、私はcollection
ロジックにview
ものを入れたくありません。これと同様に、イベントハンドラをバインドする際
代わりに、初期化関数に '_.bindAll(this)'を入れている。これは、オブジェクト内で呼び出されたすべての関数が、 'this'の値がオブジェクト自体に正しくバインドされて適用されることを保証します。たくさんのコールバックを書く場合に便利です。 – rybosome