Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 413
Daniel Szabo Avatar asked Nov 26 '10 16:11

Daniel Szabo


People also ask

How do I create a custom event?

A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.

How do you create an event object?

The createEvent() method creates an event object. The event must be of a legal event type, and must be initialized (dipatched) before use.

What are the two types of custom events?

Application Event: Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified. Component Event: A component event is fired from an instance of a component.

What is JavaScript CustomEvent?

Adding custom data – CustomEvent()To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows: const event = new CustomEvent('build', { detail: elem.


1 Answers

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();
like image 88
25 revs, 4 users 83% Avatar answered Oct 19 '22 14:10

25 revs, 4 users 83%