At last it is time to show some examples. The simpler side to illustrate is the event source, so let's start there. I've already shown how to declare events, but here's a complete example.
Base : $class(zjs.EventSource,
{
$events :
[
/**
Documentation for the foo event.
*/
"foo"
]
}),
Derived : $class("Base",
{
$events :
[
/**
Documentation for the bar event.
*/
"bar"
]
})
The above class hierarchy defines two events. The Base class defines the foo event while the Derived class inherits foo and adds the bar event.
Ready... Aim...
Now that we've declared our events, let's fire one.
this.fireEvent("foo", { x: 42 });
The above will use the zjs.Event class for events and this call will place an x property on the event instance with the value of 42. Any number of properties can be added, which forms the contract between the event source and the listener(s).
Special Cases
Perhaps an event needs a special class to represent it. This can be done by deriving a class from zjs.EventType and putting an instance in the $events array.
SpecialEventType : $class(zjs.EventType,
{
ctor : function ()
{
$super(arguments).call(this, "specevent");
},
create : function (target, params)
{
return new MySpecialEvent(target, params);
}
}),
MySpecialEvent : $class(zjs.Event,
{
ctor : function (target, params)
{
$super(arguments).call(this, "specevent", target, params);
}
}),
SpecialFellow : $class(
{
$events :
[
new SpecialEventType()
]
})
To handle the case where zjs.EventSource cannot be used as a base class:
RockAndHardPlace : $class(SomeOtherBase,
{
$events :
[
"sameoldthing"
],
fireEvent : function (name, params)
{
return zjs.fireEvent(this, name, params);
},
on : function ()
{
return zjs.subscribeEvent.apply(this, arguments);
}
})
No comments:
Post a Comment