0

I have an add method that pushes a function into an array so it can be called up later.

class FRAME.Renderer
  camera   : FRAME.__Camera
  renderer : FRAME.__Renderer 
  scene    : FRAME.__Scene 


  constructor : ( lookAt )->
    @lookAt  = lookAt or false
    @modules = []


  add : ( module )->
    self = this 

    if typeof( module ) is 'function' then @modules.push( module )
    else throw new Error( 'add() only accepts a Function' )

    this 

  build :->
    self = this 
    len  = @modules.length  

    setup =( i )->
        temp = self.modules[i].bind( self )
        temp()

    if len isnt 0 then for i in [0..len-1] then setup( i )


makeCircle =->
  # Circle stuff

makeSquare =->
  # Square stuff

renderer = new FRAME.Renderer()
renderer.add( makeCircle )
renderer.add( makeSquare )

renderer.render()

This works without any issues. How, or is it possible, to have this setup and call add with a function that has parameters ( should I use an object/array combo [{}] to hold the modules instead ) ?

makeSquare = ( options )->
  # Square stuff

renderer.add( makeSquare, options )
Foreign Object
  • 1,630
  • 11
  • 22

1 Answers1

0

Yes, this is possible, and actually quite easy with coffeescript:

add: (module, args...) ->
  if typeof module is 'function'
    @modules.push {fn: module, args: args}
  else
    throw new Error 'add() only accepts a Function'
  @
build: ->
  for {fn, args} in @modules
    fn(args...) # or
    fn.apply @, args # if you want to bind them
  @
Bergi
  • 630,263
  • 148
  • 957
  • 1,375