如何在JavaScript对象内部触发自定义事件

17

我正在努力更好地理解JavaScript中的面向对象技术。

我有以下(琐碎的)对象:

function CustomObject () {
    this.size = 1;
};

CustomObject.prototype.addSize = function () {
    this.size += 1;
    if(this.size > 5) {
        //Raise custom Event
    }
};

我是这样安装的。

   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() {}

如何在我的自定义对象中引发自定义事件,然后在父级中监听该事件?在JavaScript中是否可能实现这种操作?


谢谢。我看了一下jquery的东西,看起来不错,但好像需要DOM元素。 - David Kethel
2个回答

13

你可以通过创建自定义事件类,该类具有监听器和触发相关函数来实现。我在这篇好文章中找到了相关内容。该类的实现方式如下:

//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;
                }
            }
        }
    }
};

但是,正如作者所说,这个类并不完整,它有一些限制。因此,我建议使用jQuery代替。你可以很容易地使用bind()trigger()函数来自定义事件。关于这个问题,有一个很好的讨论主题。如果你查看jQuery中的自定义事件?,你会发现如何使用jQuery实现它。


2
感谢@Sangdol提供自定义事件对象的链接。在那个链接的启发下,我想出了以下解决方案。
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"); }

这不是一个完美的解决方案,但对于我的目的来说足够了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接