最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to raise a custom event from within a JavaScript object - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Apr 18, 2023 at 21:59 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jul 29, 2011 at 0:13 David KethelDavid Kethel 2,5509 gold badges29 silver badges49 bronze badges 1
  • Thanks for that. I had a look at the jquery stuff, it looks good except it looks like it requires DOM elements. – David Kethel Commented Jul 29, 2011 at 3:15
Add a comment  | 

2 Answers 2

Reset to default 13

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.

Thanks to @Sangdol for the link to the custom event object. Using the ideas in that I came up with the following solution

function CustomObject (type, listener) {
    this.size = 1;
    this.subscriberType = type;
    this.subscriberListener = listener;
};

CustomObject.prototype.addSize = function () {
    this.size += 1;
    if (this.size > 5) {
        this.subscriberListener.call(this.subscriberType);
    }
};

// Test the event
var myObject = new CustomObject(Document, handelCustomEvent);

myObject.addSize();
myObject.addSize();
myObject.addSize();
myObject.addSize();
myObject.addSize();
myObject.addSize();
myObject.addSize();    

function handelCustomEvent() { alert("Event"); }

Its not a perfect solution, but its enough for my purposes.

发布评论

评论列表(0)

  1. 暂无评论