我可以在Javascript中为我创建的对象创建自定义事件吗?

时间:2010-11-26 16:46:03

标签: javascript events methods object

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

/* -- 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。我将如何创建它,以及在哪里“附加”它?

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

2 个答案:

答案 0 :(得分:8)

一个简单的例子:

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();

答案 1 :(得分:0)

或者,您可以使用某些第三方框架(例如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