Last active
December 20, 2015 06:19
-
-
Save BenEddy/6084616 to your computer and use it in GitHub Desktop.
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
isFunction = (obj) -> | |
toString.call(obj) == '[object Function]' | |
Object.prototype.delegate = () -> | |
args = Array.prototype.slice.call(arguments); | |
[methods, options] = [args[0..(args.length - 2)], args[(args.length - 1)]] | |
for method in methods | |
delegation = (method, delegatedMethod) -> | |
@[method] = -> | |
target = @[options.to] | |
target = if isFunction(target) then target.apply(@) else target | |
attribute = target[delegatedMethod] | |
if isFunction(attribute) then attribute.apply(target, arguments) else attribute | |
if options.prefix | |
prefixedMethod = options.prefix + method.substr(0, 1).toUpperCase() + method.substr(1) | |
delegation.call(@prototype, prefixedMethod || method, method) | |
class Profile | |
constructor: (@name, @birthday) -> | |
getName: -> | |
@name | |
getBirthday: -> | |
@birthday | |
class User | |
@delegate "name", "getName", "getBirthday", {to: "profile", prefix: "profile"} | |
@delegate "birthday", {to: "profile"} | |
constructor: (@profile) -> | |
getProfile: -> | |
@profile | |
profile = new Profile("Kyle", "April") | |
user = new User(profile) | |
console.log user.birthday() | |
console.log user.profileName() | |
console.log user.profileGetName() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment