Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Raise a custom event from within a java script object

I am trying to get a better understanding of object orientated techniques in Java script.

I have the folowing (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 Java script?

like image 812
David Kethel Avatar asked Jul 29 '11 00:07

David Kethel


People also ask

How do I use CustomEvent in JavaScript?

A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.

Is events can be triggered by JavaScript?

HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.


1 Answers

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:

//Copyright (c) 2010 Nicholas C. Zakas. All rights reserved.
//MIT License

function EventTarget(){
    this._listeners = {};
}

EventTarget.prototype = {

    constructor: EventTarget,

    addListener: function(type, listener){
        if (typeof this._listeners[type] == "undefined"){
            this._listeners[type] = [];
        }

        this._listeners[type].push(listener);
    },

    fire: function(event){
        if (typeof event == "string"){
            event = { type: event };
        }
        if (!event.target){
            event.target = this;
        }

        if (!event.type){  //falsy
            throw new Error("Event object missing 'type' property.");
        }

        if (this._listeners[event.type] instanceof Array){
            var listeners = this._listeners[event.type];
            for (var i=0, len=listeners.length; i < len; i++){
                listeners[i].call(this, event);
            }
        }
    },

    removeListener: function(type, listener){
        if (this._listeners[type] instanceof Array){
            var listeners = this._listeners[type];
            for (var i=0, len=listeners.length; i < len; i++){
                if (listeners[i] === listener){
                    listeners.splice(i, 1);
                    break;
                }
            }
        }
    }
};

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() and trigger() 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.

like image 167
Sanghyun Lee Avatar answered Oct 13 '22 22:10

Sanghyun Lee