Backbone.js: how to stop propagation of events among nested views

I am looking for ways to make views independent. Thus, view events are limited to that view, rather than hitting the elements of the children and parent.

The backbone.js framework binds the event on the top view element (view.el) using the jQuery.on method. Since I have nested views, when I click view button B, the event will also be fired on view A. I know that I can add a handler to the button by clicking view B and return false, but this way I need to know all events parent view and always handle all these events.

An example of the problem follows: http://jsfiddle.net/57RAM/3/

I would like to click the MyViewB button and not fire the ViewA event. I tried adding 'all': -> return false

in events like B, but it didn't work.

Any suggestion?

+3


source to share


2 answers


You can use ev.stopPropagation () in the nested view click handler (MyViewB) to prevent an event starting from the DOM tree.



0


source


If the problem is that view B needs to be reused, and if you don't mind that view A knows about this, you can use more specific event selectors for view A bindings.

The example uses a simple selector "button", which will capture both buttons from view A and child view B. Using a class like ".btn" or "button.view-a" will prevent the problem.



The next snippet can be seen here using ".btn" to bind the event.

events:
    'click .btn': 'click'

click: (ev) ->
    alert('MyViewA button click')

initialize: ->
    $('<button class="btn">').text('MyViewA').appendTo(@el)
    child = new MyViewB
    $(child.el).appendTo(@el)

      

0


source







All Articles