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.
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.
The createEvent() method creates an event object. The event must be of a legal event type, and must be initialized (dipatched) before use.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With