Search code examples
ractivejs

Event overriding RactiveJS


I find myself in a little bit of trouble because triggering an event on a element will also fire the event binded to its parent element like the following.

var template = new Ractive({
  el: 'wrapper',
  template: '<div on-click="open">OPEN<div on-click="close">CLOSE</div></div>'
});

template.on({
  open: function(e) {
    alert('opening');
  },
  close: function() {
    alert('closing');
  }
});
div > div {
  display: inline-block;
  padding: 10px;
  background: rgba(0, 0, 0, .3);
  padding: 10px 10px 10px 50px;
  cursor: pointer
}
<script src="https://cdn.ractivejs.org/latest/ractive.js"></script>
<div id="wrapper"></div>


Solution

  • You can stop a DOM event bubbling by calling its stopPropagation method. The event argument passed to Ractive event handlers stores the original DOM event as event.original - so you can do it like so:

    var template = new Ractive({
      el: 'wrapper',
      template: '<div on-click="open">OPEN<div on-click="close">CLOSE</div></div>'
    });
    
    template.on({
      open: function(e) {
        alert('opening');
      },
      close: function(e) {
        alert('closing');
        e.original.stopPropagation();
      }
    });
    div > div {
      display: inline-block;
      padding: 10px;
      background: rgba(0, 0, 0, .3);
      padding: 10px 10px 10px 50px;
      cursor: pointer
    }
    <script src="https://cdn.ractivejs.org/latest/ractive.js"></script>
    <div id="wrapper"></div>