Created
November 23, 2012 23:57
-
-
Save partkyle/4137758 to your computer and use it in GitHub Desktop.
Coffeescript Delegates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Something | |
constructor: -> | |
@delegateObject = new Messager | |
class Messager | |
testing: (int) -> | |
console.log int | |
woot: (bool) -> | |
console.log bool | |
nothing: (array) -> | |
console.log array | |
Object::delegates = (methods, to) -> | |
methods.forEach (method) => | |
this::[method] = (args...) -> | |
@[to][method].apply(this, args) | |
Something.delegates(['testing','woot','nothing','missing'], 'delegateObject') | |
s = new Something | |
s.testing(1) | |
s.woot(false) | |
s.nothing([1,2,4]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Something, Messager; | |
Something = (function() { | |
function Something() { | |
this.delegateObject = new Messager; | |
} | |
return Something; | |
})(); | |
Messager = (function() { | |
function Messager() {} | |
Messager.prototype.testing = function(int) { | |
return console.log(int); | |
}; | |
Messager.prototype.woot = function(bool) { | |
return console.log(bool); | |
}; | |
Messager.prototype.nothing = function(array) { | |
return console.log(array); | |
}; | |
return Messager; | |
})(); | |
Object.prototype.delegates = function(methods, to) { | |
var _this = this; | |
return methods.forEach(function(method) { | |
return _this.prototype[method] = function() { | |
var args; | |
args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; | |
return this[to][method].apply(this, args); | |
}; | |
}); | |
}; | |
Something.delegates(['testing', 'woot', 'nothing', 'missing'], 'delegateObject'); | |
s = new Something; | |
s.testing(1); | |
s.woot(false); | |
s.nothing([1, 2, 4]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've just googled it and it helped me a lot. Really awesome!