Ted Patrick > { Events & Community } > Adobe Systems


I wrote this constructor function that produces wrapper methods. It returns a wrapper for the function passed as an argument. The key is that it allows you to append events on either end of execution and substitute the arguments array. It is a fairly simple way to extend functions in-situ via events or conditionally modify the arguments array on execution.

// wrap the trace method
a = wrap(trace)

//NOTE: 'new' breaks the functionality as return is ignored.

//execute it
a('Hello') //output: Hello

//add some events
a.onstart = function(a){trace('a.onstart '+a)}
a.onend = function(a){trace('a.onend '+a)}

a('Hello')
//output: a.onstart Hello
//output: Hello
//output: a.onend Hello

//add a substitute arguments object
a.arguments = ['New Hello']

a('Hello')
//output: a.onstart Hello
//output: New Hello
//output: a.onend Hello

Or how about wrapping a method of MovieClip.prototype

MovieClip.prototype.getDepth = wrap(MovieClip.prototype.getDepth)
MovieClip.prototype.getDepth.onstart = function(){trace('before')}
MovieClip.prototype.getDepth.onend = function(){trace('after')}

Here is the wrap method:

_global.wrap = function(s){
  return function(t){
    var self = arguments.callee
    var r
    self.onstart.apply(self,arguments)
    if(self.arguments) {
      r = s.apply(this,self.arguments)
    }else{
      r = s.apply(this,arguments)
    }
    self.onend.apply(self,arguments)
    return r
  }
}

a = wrap(trace)
a.onstart = function(a){trace(' a wrap onstart a:'+a)}
a.onend = function(a){trace(' a wrap onend a:'+a)}
a.arguments = ['a custom arguments']

b = wrap(a)
b.onstart = function(a){trace(' b wrap onstart a:'+a)}
b.onend = function(a){trace(' b wrap onend a:'+a)}
b.arguments = ['b custom arguments']

c = wrap(b)
c.onstart = function(a){trace('c wrap onstart a:'+a)}
c.onend = function(a){trace('c wrap onend a:'+a)}
c.arguments = ['c custom arguments']

c('hello')

Enjoy,

ted ;)

0 Responses to “ Wrapper Constructor with events and substitute arguments ”

Post a Comment



© 2008 Ted On Flash