documentcloud/backbone — pull request #1954 by derickbailey (2012-12-17 14:30:58+00:00)
Title: add context as 4th parameter to listenTo and stopListening methods on Backbone.Events

When building event aggregators. event hubs, mediators, and other objects with Backbone.Events, you need to be able to specify the context in which an event callback is executed. With the standard `on` and `off` methods, this works just fine, but the new `listenTo` and `stopListening` methods lacked a `context` parameter to handle this.

Example: a mediator object that coordinates between two views

```js
var mediator = _.extend({

// run the app with this mediator object
run: function(){
this.setupFirstView();
this.setupSecondView();
},

// shut down the mediator and unbind all the events
close: function(){
this.stopListening();
},

setupFirstView: function(){
var view = new MyView();

// need to be able to specify the 4th parameter of context, here
this.listenTo(view, "foo", this.doStuff, this);

view.render():
$("#foo").empty().append(view.$el);
},

setupSecondView: function(){
this.anotherView = new AnotherView();
this.anotherView.render();

$("#bar").empty().append(this.anotherView.$el);
},

// the event handler needs to be able to call the
// mediator's "this.anotherView", so we need to know
// that the context is correct
doStuff: function(){
this.anotherView.hideThat();
this.anotherView.showThis();
}

}, Backbone.Events);

// somewhere in the app:
mediator.run();

// somewhere else in the app:
mediator.close();
```

This is a very common pattern in my applications, with the use of MarionetteJS.

Up until now, I've been using my Backbone.EventBinder to handle this situation. But with the inclusion of `listenTo` and `stopListening` in Backbone.Events, I want to deprecate Backbone.EventBinder. I need to have this 4th parameter for context available in order to do that without resorting to `bind`, `apply`, and `call` function calls everywhere.

This PR adds the 4th parameter to both, with test to show functionality, and minor tweaks to the docs.