Daniel Szabo
Daniel Szabo

Reputation: 7281

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

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.

Upvotes: 10

Views: 8977

Answers (2)

gblazex
gblazex

Reputation: 50109

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

Upvotes: 8

Tengiz
Tengiz

Reputation: 8429

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

Upvotes: 0

Related Questions