Reputation: 3738
I have an EditorView subview associated with one Model
that renders a series of form elements (input checkbox, textarea).
My ListView creates one and only one Editor sub view. ListView creates the EditorView by way of new EditorView(model: this.model). render();
on a click of an item in the ListView.
That works great.
But, when an event is attached to the Editor subview
// Bind to all properties in the view
events: {
"click input.isactive": "editActive"
},
The event gets fired multiple times...once per previously loaded EditorViews. As if the html for many was still present. But checking the DOM (in Firefox) shows the html for only one EditorView.
I use .html(string) in EditorView, which I thought would replace the previous html within the 'el' element.
var compiledTemplate = _.template( Template, data ); // Merge model with template
this.$el.html( compiledTemplate ); // replace the previous html if any. ?? OR NOT!! SOAD
Thanks
The EditorView
el: ".editor",
tagName: "ul",
className : "striped",
events: {
"click .isactive": "editActive"
},
render : function() {
var data = {
item: this.model,
_: _
};
var compiledTemplate = _.template( Template, data ); // Merge model with template
this.$el.empty().html( compiledTemplate ); // replace the previous html
return this;
},
editActive: function(e) {
e.preventDefault();
var x = this.$('.isactive').prop('checked'); // property of input checkbox
alert('click'+x);
var y = this.model.set('Active', x);
}
Upvotes: 0
Views: 177
Reputation: 2050
Backbone attaches handlers to a root element of a view, so callbacks are registered multiple times when you create several views with the same root element. It uses event bubbling to detect events that were triggered on a child element. The problem is with this line:
el: ".editor",
Even if you remove all of the contents of .editor
, handlers for the element itself will stay. You need either to delete it, or if you want to keep it you can use the undelegateEvents
method of the view before creating a new one: it will remove previously attached event handlers.
Upvotes: 1