Marionette.Controller.listenAll

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…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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.

1
2
3
4
5
6
7
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.