jmasterx
jmasterx

Reputation: 54113

Listeners in JavaScript?

I am new to javascript.

Here is what I need to be able to do (preferably without JQuery or any other external library).

When a certain event happens, I want to notify the user via a callback. I am wondering how I should go about doing this.

I have a class that I am working on (a function of functions)

and ideally I would like the user to be able to set callbacks something like this:

function myOnTouch(front,back) {
//do stuff
}

apiInstance.onTouch = myOnTouch;

I am not sure if this is how JavaScript works, but if someone could point me in the right direction on creating callbacks for JavaScript classes, I would really appreciate it.

Thanks

Upvotes: 0

Views: 70

Answers (1)

Barmar
Barmar

Reputation: 780909

When your class wants to notify the user, it simply calls the callback:

if (this.onTouch) {
    this.onTouch(this.front, this.back);
}

You could also have multiple callbacks, and do:

for (var i = 0; i < this.onTouch.length; i++) {
    this.onTouch[i](this.fron, this.back);
}

You can then provide an API to add listeners:

apiInstance.addOnTouch(myOnTouch);

The implementation would look like:

function addOnTouch(callback) {
    this.onTouch.push(callback);
}

Upvotes: 2

Related Questions