Tengo el siguiente código:Backbone esta confusión
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);
}
});
Mi problema está dentro de la función appendItem
. Cuando uso this
dentro de la función appendItem
, creo que cree que el this
se refiere al this.collection
en lugar del GoalPanelView
. ¿Cómo obtendré el this
para referirme al GoalPanelView
en lugar del collection
? Intenté pasar otra variable a la función appendItem
que contenía los contenidos de this.elem
, pero no pareció funcionar.
Una cosa que funcionó fue cuando me cambiaron la función appendItem
en el collection
y cambió la inicialización de unirse a this.collection.bind('add', appendItem);
pero no quiero poner las cosas view
en la lógica collection
.
Una alternativa es poner '_.bindAll (this)' en la función de inicialización. Eso asegura que cualquier función llamada dentro del objeto será aplicada con el valor de 'this' ligado apropiadamente al objeto mismo. Útil si estás escribiendo muchas devoluciones de llamada. – rybosome