Subscribing and Unsubscribing to an event


Google
You can subscribe to an event in a lot of different way. By adding attribute to html element. By using addEventListener or by inline subscription in JavaScript.

Here is our simple button without any attribute

<input type="button" value="Submit" id="btn"/>

Subscribing using HTML Attribute

HTML

<input type="button" value="Submit" onClick="HelloWorld()" id="btn" />

JavaScript

function HelloWorld(){

alert("Hello World");

}

In this example, the button is subscribed to the Click event. When ever the button is pressed or click. It will call HelloWorld() function. There are a lot of events we can subscribe to. In the onClick property we specify the function to call.

Subscribing using addEventListener

HTML:

<input type="button" value="Submit" id="btn"/>

JavaScript:

var btn = document.getElementById("btn");
btn.addEventListener("click",HelloWorld,false);
function HelloWorld(){
alert("Hello World");
}

Note that there are three parameters. The first one is the event name, the second one is the function to call and the last and the third one is true in case of event capturing and false in case of event bubbling. Mostly we use false here.

If you need explanation on event capturing & event bubbling Click Here

Inline Subscription

HTML:

<input type="button" value="Submit" id="btn"/>

JavaScript:

var btn = document.getElementById("btn");
btn.onclick =  HelloWorld;
function HelloWorld(){
alert("Hello World");
}

Unsubscribing From An Event

Unsubscribing from an event is usually done using the removeEventListener function which is called on the object of which event you want to remove.

JavaScript:

var btn = document.getElementById("btn");
btn.removeEventListener("click",HelloWorld,false);
function HelloWorld(){
alert("Hello World");
}

Usually, the parameters of the removeEventListener is the same as addEventListener.

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