javascriptbackbone.jsbackbone-viewsbackbone-events

Nested views : binding events with proper ui


I have app where one type of view is nested in same type. Something like this http://take.ms/ylAeq

How can I catch event on view button and fired event on proper view?

I have situation when I have ~10 fired events becuase backbone binds event to all inner buttons, not only button of proper view.

I have one idea - I make in template id="node_body_<%= id %>" so each button id based on it's view's model id; but how can I pass it to events object? events :{ "click #node_body_" + id : 'method' } doesn't work.


Solution

  • The issue is event bubbling. The events on your inner view's bubble upto the el of it's parent view's, which is listening for events on same selector, in turn triggering it's handler.

    This can be fixed by stopping the propagation of event in the respective view's handler:

    Backbone.View.extend({
      events: {
        'click .thing': 'do_thing'
      },
      do_thing: function(event) {
        event.stopPropagation(); // prevents event reaching parent view
      }
    });