Skip to content

Instantly share code, notes, and snippets.

@BenEddy
Last active December 20, 2015 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenEddy/6084616 to your computer and use it in GitHub Desktop.
Save BenEddy/6084616 to your computer and use it in GitHub Desktop.
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