I know you can create a CustomEvent
like this:
var wordCreated = new CustomEvent(
"newWord",
{
detail: {
word: "hola",
translation: "hi",
},
bubbles: true,
cancelable: true
}
);
I'm wondering how to do this without using new
, with the Object.create
pattern?
The problem I’m not seeing a solution to is that the CustomEvent
takes two arguments: a string specifying a name for the event, and a configuration object containing bubbles
, cancelable
, and details
properties. I’m not sure how to pass both the string and the object to Object.create
.
Ultimately I expect to be able to use this custom event in the following standard way:
var p = document.querySelector('p'); // a random node
p.addEventListener('newWord', function(ev){ console.log(ev) });
p.dispatchEvent(wordCreated);
The answer to the question in your title "Is it possible to use the Object.create pattern to create a CustomEvent object?" is Yes. Now, the answer to the follow-up question "Shall you do it that way?" is probably No. As @MartinErnst pointed out, you're just going to end up re-inventing the wheel of what
new
is already doing.The key difference between
new
andObject.create
(in case you don't already know) is thatObject.create
creates anObject
(notice the uppercase O) which inherits the prototype of the object specified as the first argument ofObject.create
. Thenew
operator does the same thing with the additional step of invoking the constructor of the given object, before returning an instance of the specified object (notice the lowercase o).So we can use
Object.create
to create anObject
which inherits from theCustomEvent
prototype with something like this:But doing a
console.log(customEvent1)
will yield anObject
.Contrast this to:
You will see that running
console.log(customEvent2);
will yield an instance ofCustomEvent
.So when you try to invoke
addEventListener()
anddispatchEvent()
on the abovecustomEvent1
object, it will fail because that is anObject
, not anEvent
. There are a few more things steps you will need to do to convertcustomEvent1
into a fullEvent
object, which is essentially whatnew CustomEvent()
is already doing.Fiddle available here.