javascript 如何从 Java 脚本对象中引发自定义事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6867283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:08:42  来源:igfitidea点击:

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

javascriptjavascript-events

提问by David Kethel

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

我试图更好地理解 Java 脚本中的面向对象技术。

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?

如何在自定义对象中引发自定义事件,然后在父对象中侦听该事件?这种事情在Java脚本中甚至可能吗?

采纳答案by Sanghyun Lee

You can do it by making your custom event class which has listener and trigger related functions. I found a good articleabout 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.

但是,正如作者所说,这门课并不完整。它有一些限制。所以我建议改用jQuery。您可以轻松地使用自定义事件bind()trigger()函数。有一个关于这个的好话题。如果您在 jQuery 中看到自定义事件?,您将了解如何使用 jQuery 实现它。

回答by David Kethel

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

感谢@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"); }

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

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