Creating events on variables in Javascript

Handling an event on an array in Javascript is a common task. One of the most common scenarios is creating a custom control and triggering an event when a change happens in this control. I’ll explain a simpler scenario; when you are doing something behind the scenes and updating an array.Then, you’d want to notify the user with the added object.

The following steps are the main steps to create an event

First, we define an array with some values and an other array to hold the event handlers for the event that we need to trap.
var shapes = ["Rectangle", "Square", "Triangle"];
//an array to hold the name of methods registered as the event handlers
//for the onchange event.
var OnArrayChange = [];

Second, we create a method that adds the event handlers to the OnArrayChange array.
function RegisterOnArrayChangeEvent(methodName) {
OnArrayChange.push(methodName);
}

Third, we create a method that raises the event. The method will call each registered event handler and specify the updated of the shapes array.
function RaiseOnArrayChange(obj) {
//a loop through all registered event handlers and call them
for (var i = 0; i < OnArrayChange.length; i++) {
OnArrayChange[i](obj);
}
}

Fourth, we create a method that adds a new shape to the shapes array. Then, it raises the ArrayChange event.
function AddShape(shape) {
var len = shapes.push(shape);
//fire the change event
RaiseOnArrayChange(len);
}

The next step is used to wire an event handler with the event.

Fifth, we create the event handler for then ArrayChange event. The user will be alerted with the updated length.
function ArrayChangeEventHandler(length) {
alert(length);
}

Sixth,we register the event handler to the OnArrayChange event. and add the shape “Circle” to the array
function CreateShapes() {
//bind the event handler to the event
RegisterOnArrayChangeEvent(ArrayChangeEventHandler);
AddShape("Circle");
}

Finally, we call the CreateShapes method to begin the execution of the code.
CreateShapes();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: