开发者

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

开发者 https://www.devze.com 2023-01-26 21:51 出处:网络
Assume I have an object with a member function that returns itself: /* -- Object 1 -- */ function Object1(){

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, s开发者_JS百科uppose 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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消