Question

I'm having trouble figuring out how to quickly, and simply attach a listener for events triggered on a Backbone.Marionette view.

I can currently accomplish what I'm looking for by adding a listener via .on, but is there a quick way via the events or triggers hashes? Something like this seems like it should work but doesn't:

return Marionette.ItemView.extend({      
    triggers: {
        "click .close": "menu:close"
    },

    events: {
        "menu:close @": "close",
    },

    close: {
        // do stuff
    }
}
Was it helpful?

Solution

Update
There is actually a (simple) way to do exactly what you want.

// Itemview
var itemView = Marionette.ItemView.extend({
    initialize: function() {
        Marionette.bindEntityEvents(this, this, this.events);  
    },
    template: "#item",
    triggers: {
        "click .btn": "menu:performAction"
    },
    events: {
        "menu:performAction": "performAction"
    },
    performAction: function() {
        console.log('test');
    }
});

In short this binds your events attribute containing the hashes to the views events.

Fiddle: http://jsfiddle.net/8T68P/
Documentation: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.functions.md#marionettebindentityevents

Old answer
See this fiddle: http://jsfiddle.net/Cardiff/K5TTQ/

Listening to events like that won't work indeed. And if you happen to use the .on method from within your view. Please use listenTo. That will be cleaned up properly when the view is closed. Like this:

// Itemview
var itemView = Marionette.ItemView.extend({
    initialize: function() {
        var view = this;
        view.listenTo(view, "menu:performAction", view.performActionFromListenTo);   
    },
    template: "#item",
    triggers: {
        "click .btn": "menu:performAction"
    },        
    performActionFromListenTo: function() {
        console.log('test');
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top