10

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.

2 Answers 2

8

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();
Sign up to request clarification or add additional context in comments.

4 Comments

This looks like it will execute the onPublish() event before the image is returned (if that's not the case, please let me know). What would I do if I wanted it to fire after the return, instead?
What to you mean "before the publish method has returned the image"? The onPublish() method is called before the publish() call returns, of course, but do you mean after the image has been loaded?
@ajax81 - I've updated the example. Now it's async, so it will add the callback to the event loop, just like how an event handler should be.
Ah. I see. Much thanks, galambazs. I appreciate your time.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.