Can I create a custom event in Javascript for an object I created?

假装没事ソ 提交于 2019-12-20 19:56:50

问题


Assume I have an object with a member function that returns itself:

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

In production:

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

Now, suppose I wanted to create an event that fires when the object's publish() method is called, but after the image is returned (something akin to an "onPublished()" event). Say, to to change the image dimensions to 100x100. How would I create it, and where would I "attach" it?

If I'm not being clear enough, please let me know. This is the simplest demo I could think of.


回答1:


A simple example:

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



回答2:


Alternatively, you can use some 3rd party framework (such as bob.js) to define custom events on your objects. There are two approaches, but I will show only one:

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


来源:https://stackoverflow.com/questions/4287108/can-i-create-a-custom-event-in-javascript-for-an-object-i-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!