EventBroadcaster for Director

You have to implement via Decorator pattern (think that’s the one…) instead of using initialize, but so far, seems to work. The only issue is, I am still trying to figure out how to do Function.apply in Director… because currently, I’m just passing the parameters as an array to the call method; which was the point of Function.apply being able to have any number parameters passed as an array, and then doing the argument distribution for you. At any rate, here’s what I got:
<pre><code>
property pListeners

on new me
init()
return me
end

on init me
pListeners = []
end

on broadcastMessage me, msg
howMany = pListeners.count()
repeat with n = 1 to howMany
o = pListeners[n]
if o.handler(msg) = true then
l = paramCount()
a = []
repeat with i = 2 to l
a.append(param(i))
end repeat
call(Symbol(msg), o, a)
end if
end repeat

end

on addListener me, obj
pListeners.append(obj)
end

on removeListener me, obj
howMany = pListeners.count()
repeat with n = 1 to howMany
if pListeners[n] = obj then
pListeners.deleteProp(n)
return true
end if
end repeat
return false
end
</code></pre>

And you can implement in your Parent Scripts (or behaviors I guess) like so:
<pre><code>
property pBroadcaster

on new me
init()
end

on init me
pBroadcaster = script(“EventBroadcaster”).new()
end

on addListener me, obj
pBroadcaster.addListener(obj)
end

on removeListener me, obj
success = pBroadcaster.removeListener(obj)
return success
end

on broadcastMessage me, msg
pBroadcaster.broadcastMessage(msg, param1, paramN)
end
</code></pre>

…still, would be great to figure out how to pass dynamic amounts of parameters like you can in Flash using Function.apply…

2 Replies to “EventBroadcaster for Director”

  1. Jesse, you might be interested in knowing that you can simplify your broadcastMessage code. If you use a list in a call() method instead of a single object reference, it will send your event message to all script objects in that list. It has the added benefit of NOT causing an error if one of those script instances doesn’t have a handler for the event you’re sending, thus eliminating the need to check for the handler as you’re doing above.

    The new simplified code would look like this:

    ===>

    on broadcastMessage me, msg

    l = paramCount()
    a = []
    repeat with i = 2 to l
    a.append(param(i))
    end repeat

    call(Symbol(msg), pListeners, a)

    end

    ===

    P.S. Bummer that these comments don’t support ANY indenting!!!!

  2. I didn’t use a list because I didn’t remember the docs saying that it didn’t cause an error. If that’s the case, then schweeet!!! Thanks for that.

    If you want tabbing, write your comment in notepad, and paste in here, then wrap it with “pre” tags.

Comments are closed.