0

I have a model relationship set-up with Backbone Relational, whereby an Item belongs to a Column. Adding items to columns works well, but how do I reference an existing view for an item, in-order to remove it from its old column? (Therefore, items are currently duplicating across columns.)

Please see this JSFiddle - http://jsfiddle.net/geVPp/1 (I presume code will need to be implemented in the ColumnView removeItem event handler, but I may be wrong).

(The example instantiation is at the bottom of the script, as I have no UI controls yet.)

Here is the ColumnView from the fiddle:

var ColumnView = Backbone.View.extend({
className: 'column',
tagName: 'div',
template: Handlebars.compile($('#column-template').html()),
initialize: function() {
  _.bindAll(this, 'render', 'renderItem', 'removeItem');
  this.model.bind('change', this.render);
  this.model.bind('reset', this.render);
  this.model.bind('add:items', this.renderItem);
  this.model.bind('remove:items', this.removeItem);
},
render: function() {
  return $(this.el).html(this.template(this.model.toJSON()));
},
renderItem: function(item) {
  var itemView = new ItemView({model: item});
  this.$('.items').append($(itemView.render()));
},
removeItem: function(item) {
  // @todo -- How do I reference the item model's view, in order to remove the DOM element?
}
});
joecritch
  • 1,095
  • 2
  • 10
  • 25

1 Answers1

0

Unfortunately Backbone has no built-in way; you have to keep track of your child views (and which model they map to) manually.

Backbone.Marionette has a CollectionView class that can automate this for you. Or you could roll your own similar to UpdatingCollectionView.

If you want a quick fix, you could keep a reference to the view as a variable of the model object, but that's bad because it prevents you from showing multiple views of the same model.

gmcnaughton
  • 2,233
  • 1
  • 21
  • 28