简体   繁体   中英

backbone event fired many times

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(); 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);
  }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM