【问题标题】:Can I create a custom event in Javascript for an object I created?我可以在 Javascript 中为我创建的对象创建自定义事件吗?
【发布时间】:2011-05-16 06:50:59
【问题描述】:

假设我有一个带有返回自身的成员函数的对象:

/* -- Object 1 -- */
function Object1(){
    this.me      = new Image(10,10);
    this.me.src  = "someImgUrl.jpg";
    this.publish = function(){
        return this.me;
    }
}

生产中:

var Obj1 = new Object1();
document.body.appendChild( Obj1.publish() );

现在,假设我想创建一个在调用对象的 publish() 方法时触发的事件,但在图像返回之后(类似于“onPublished()”事件)。比如说,将图像尺寸更改为 100x100。我将如何创建它,我将在哪里“附加”它?

如果我不够清楚,请告诉我。这是我能想到的最简单的演示。

【问题讨论】:

    标签: javascript events methods object


    【解决方案1】:

    一个简单的例子:

    function Object1() {
        'use strict';
    
        this.me = new Image(10, 10);
        this.me.src = "someImgUrl.jpg";
        this.publish = function() {
            if (typeof this.onPublish === "function") {
                setTimeout(this.onPublish, 1);
            }
    
            return this.me;
        };
    }
    
    var Obj1 = new Object1();
    Obj1.onPublish = function() {
      // do stuff
    };
    
    Obj1.publish();
    

    【讨论】:

    • 这看起来会在图像返回之前执行 onPublish() 事件(如果不是这样,请告诉我)。如果我希望它在返回后触发,我会怎么做?
    • “在发布方法返回图像之前”是什么意思?当然,onPublish() 方法是在 publish() 调用返回之前调用的,但你的意思是在图像加载之后吗?
    • @ajax81 - 我已经更新了这个例子。现在它是异步的,所以它会将回调添加到事件循环中,就像事件处理程序应该是一样的。
    • 啊。我知道了。非常感谢,galambazs。感谢您的宝贵时间。
    【解决方案2】:

    或者,您可以使用一些第 3 方框架(例如 bob.js)在您的对象上定义自定义事件。有两种方法,但我只展示一种:

    var DataListener = function() { 
        var fire = bob.event.namedEvent(this, 'received'); 
        this.start = function(count) { 
            for (var i = 0; i < count; i++) { 
                fire(i + 1); 
            } 
        }; 
    }; 
    var listener = new DataListener(); 
    listener.add_received(function(data) { 
        console.log('data received: ' + data); 
    }); 
    listener.start(5); 
    // Output: 
    // data received: 1 
    // data received: 2 
    // data received: 3 
    // data received: 4 
    // data received: 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多