jquery link

my custom css

slimbox 2

analytics

Thursday, October 14, 2010

Creating custom event in JavaScript...

First, define custom event.
    var CustomEvent = function() {
//name of the event
this.eventName = arguments[0];
var mEventName = this.eventName;

//function to call on event fire
var eventAction = null;

//subscribe a function to the event
this.subscribe = function(fn)
{
eventAction = fn;
};

//fire the event
this.fire = function(sender, eventArgs)
{
if(eventAction != null)
{
eventAction(sender, eventArgs);
}
else
{
alert('There was no function subscribed to the ' + mEventName + ' event!');
}
};
};
Then create an event handler.
    var myEvent = new CustomEvent("helloworld event");
myEvent.subscribe(event_triggered);

function event_triggered(sender, eventArgs)
{
alert("hello world");
}
Now, the triggering part.
    ...
if(typeof(myEvent) != "undefined")
{
myEvent.fire(null, {
message: 'you just witnessed the firing of a custom event called ' + this.eventName + '!'
});
}
...

No comments:

Post a Comment