Skip to content

Instantly share code, notes, and snippets.

@ejoubaud
Created August 12, 2013 10:08
Show Gist options
  • Save ejoubaud/6209669 to your computer and use it in GitHub Desktop.
Save ejoubaud/6209669 to your computer and use it in GitHub Desktop.
Rails-like `delegate` in Coffeescript
# Micro-optimized, with extra-function (so it's not redefined at each call)
delegate = (delegatorConstructor, delegeeProp, method) ->
delegatorConstructor.prototype[ method ] = ->
this[ delegeeProp ][ method ].apply( this[ delegeeProp ], arguments )
Function.prototype.delegate = ( methodNames..., toProp ) ->
delegeeProp = toProp.to
for method in methodNames
delegate(this, delegeeProp, method)
# Without `that`, one method
Function.prototype.delegate = ( methodNames..., toProp ) ->
delegeeProp = toProp.to
for method in methodNames
do (constr = this, delegeeProp, method) ->
constr.prototype[ method ] = ->
console.log this
this[ delegeeProp ][ method ].apply( this[ delegeeProp ], arguments )
// Ready to use JS version, generated from the Coffeescript (= ugly...)
var __slice = [].slice;
Function.prototype.delegate = function() {
var delegeeProp, method, methodNames, toProp, _i, _j, _len, _results;
methodNames = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), toProp = arguments[_i++];
delegeeProp = toProp.to;
_results = [];
for (_j = 0, _len = methodNames.length; _j < _len; _j++) {
method = methodNames[_j];
_results.push((function(constr, delegeeProp, method) {
return constr.prototype[method] = function() {
console.log(this);
return this[delegeeProp][method].apply(this[delegeeProp], arguments);
};
})(this, delegeeProp, method));
}
return _results;
};
# With `that`, one method
Function.prototype.delegate = ( methodNames..., toProp ) ->
delegeeProp = toProp.to
that = this
for method in methodNames
do (method) ->
that.prototype[ method ] = ->
this[ delegeeProp ][ method ].apply( this[ delegeeProp ], arguments )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment