I am trying to get a better understanding of object orientated techniques in JavaScript.
I have the following (trivial) object:
function CustomObject () {
this.size = 1;
};
CustomObject.prototype.addSize = function () {
this.size += 1;
if(this.size > 5) {
//Raise custom Event
}
};
And I am instating it like this.
var myObject = new CustomObject();
myObject.addSize();
// Add listener for custom event from with in my Custom Object.
// Something like this....
myObject.addEventListener("CustomEvent", handelCustomEvent, false);
function handelCustomEvent() {}
How do I raise a custom event in my custom object and then listen to that event in the parent? Is this kind of thing even possible in JavaScript?
You can do it by making your custom event class which has listener and trigger related functions. I found a good article about this. The class is implemented like this:
But, as the writer said this class isn’t complete. It has some limitations. So I recommend using jQuery instead. You can use your custom event easily with
bind()andtrigger()function. There’s a good thread about this. If you see Custom events in jQuery?, you’ll find out how to implement it with jQuery.