3
\$\begingroup\$

I have a parent view which has a dblclick event handler bound to it. I also have a view which is a descendant of the parent. This child view has a click event handler bound to it.

Currently, my code works as intended, but looks like this:

var ParentView = Backbone.Marionette.ItemView.extend({
    events: {
        'dblclick': '_playInStream'
    },

    _playInStream: function () {
        console.log("ParentView _playInStream");
    }
});

var ChildView = Backbone.Marionette.ItemView.extend({
    events: {
        'click': '_addToStream',
        'dblclick': '_addToStream'
    },

    _addToStream: _.debounce(function () {
        console.log("ChildView _addToStream");

        //  Don't allow dblclick to bubble up to the list item and cause a play.
        return false;
    }, 100, true)
});

The end result of this logic is:

  • Single-click on child view runs _addToStream (once)
  • Double-click on child view runs _addToStream (once)
  • Double-click on parent view runs _playInStream (once)

However, I feel like the way I am expressing this code is overly convoluted, but I also don't see a better way.

The debounce is necessary because double-clicking on ChildView will execute both the click and dblclick event handlers -- but I only want a single event to run.

If I remove the dblclick event handler from the child then a dblclick will propagate up to the parent which is not desireable.

Does anyone see a better way to achieve what I want?

\$\endgroup\$
3
\$\begingroup\$

I'm not sure what seems convoluted to you. It's a simple piece of code, and if you remove anything from it, it will fail to do what you want, as you noted yourself:

  • If you remove the debounce, the method will be fired 3 times: once for the single click + twice for the double-click. So you need that.
  • If you remove the double click handler, then it will be fired in the parent

There is one thing you could "optimize", in the ChildView you could make the dblclick handler do nothing:

var ChildView = Backbone.Marionette.ItemView.extend({
    events: {
        'click': '_addToStream',
        'dblclick': function() {}
    },

This will work, because the dblclick will also trigger click, so _addToStream will be called. You still cannot remove the debounce, because without it the dblclick will trigger 2 click events.

Finally, the ChildView doesn't extend the ParentView, maybe that's a typo, and your real intention was this:

var ChildView = ParentView.extend({
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Well, I'm glad it seems sane to you. Just felt like too much to get a distinct click events, but I'll go with it. Thanks. \$\endgroup\$ – Sean Anderson Aug 27 '14 at 0:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.