Skip to content

Instantly share code, notes, and snippets.

@thegrubbsian
Created September 8, 2012 04:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thegrubbsian/3671728 to your computer and use it in GitHub Desktop.
Save thegrubbsian/3671728 to your computer and use it in GitHub Desktop.
Proxy or forward Backbone events through a mediator
(function() {
var proxy = function(source, eventName) {
var _self = this;
source.on(eventName, function(evt) {
var args = Array.prototype.slice.apply(arguments).splice(1);
args.unshift(evt);
_self.trigger.apply(_self, args);
});
};
Backbone.View.prototype.proxyEvent = proxy;
Backbone.Model.prototype.proxyEvent = proxy;
Backbone.Collection.prototype.proxyEvent = proxy;
Backbone.Router.prototype.proxyEvent = proxy;
var forward = function(target, eventName) {
var _self = this;
_self.on(eventName, function(evt) {
var args = Array.prototype.slice.apply(arguments).splice(1);
args.unshift(evt);
target.trigger.apply(target, args);
});
};
Backbone.View.prototype.forwardEvent = forward;
Backbone.Model.prototype.forwardEvent = forward;
Backbone.Collection.prototype.forwardEvent = forward;
Backbone.Router.prototype.forwardEvent = forward;
})();
@thegrubbsian
Copy link
Author

This adds a forwardEvent and proxyEvent method to Backbone Models, Views, Collections, and Routers. The forwardEvent method listens for events triggered on the current object and triggers them on the target. The proxyEvent method listens for events on the source object and triggers them on the current object.

@jkeen
Copy link

jkeen commented May 4, 2013

Shouldn't line 7 and 21 be this?

args.unshift(eventName);

As is it's not forwarding the event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment