If you’ve used Marionette for a while, you’ll find that there is still quite a bit of boilerplate to write. This doesn’t bother me that much but I’ve noticed a very familiar pattern in my marionette controllers. It looks a lot like this…
App.module('Sidebar.Show', function(Show, App, Backbone, Marionette, $, _) {
Show.Controller = Marionette.Controller.extend({
initialize : function() {
var foobars = App.request('foobar:entities');
var view = new Show.View();
App.execute('when:done', foobars, function() {
App.Region_Content.show(view);
});
this.listenTo(view, 'some:event', this.onSomeEvent);
// ... may have several events on the view
this.listenTo(view, 'something:clicked', this.onSomethingClicked);
this.listenTo(view, 'something:else', this.onSomethingElse);
},
onSomeEvent : function() {
// ...
},
onSomethingClicked : function() {
// ...
}
onSomethingElse : function() {
// ...
}
});
});
Like I said, I have no problem with writing a little extra code to help clarify things, but here is one of those cases where I think I can cut down on some boilerplate. Notice below the code is almost identical except I cut out the this.listenTo
and just use a this.listenAll
App.module('Sidebar.Show', function(Show, App, Backbone, Marionette, $, _) {
Show.Controller = Marionette.Controller.extend({
initialize : function() {
var foobars = App.request('foobar:entities');
var view = new Show.View();
App.execute('when:done', foobars, function() {
App.Region_Content.show(view);
});
this.listenAll(view);
},
onSomeEvent : function() {
// ...
},
onSomethingClicked : function() {
// ...
}
onSomethingElse : function() {
// ...
}
});
});
So now that you see how listenAll
works, the next logical question is, how do I get it into my marionette application? Easy, just use the code below. Notice I’m not doing a Marionette.Controller.extend({})
here primarily because I like this function so much I wanted it baked naively into the Marionette.Controller
.
Marionette.Controller.prototype.listenAll = function(obj) {
var controller = this;
this.listenTo(obj, 'all', function() {
controller.triggerMethod.apply(this, arguments)
});
}
That about sums it up. The last thing I’d like to say is that the triggerMethod
function is pretty neat. There is a lot that can be learned by just skimming through the Marionette annotated source.