How do I get a custom element definition without instantiating it?

134 Views Asked by At

After looking at the custom element spec, it's not immediately obvious how I get a reference to a custom element definition without first instantiating it (which can be problematic). Is there a way to directly reference a custom element's prototype?

More concretely, if I have:

var proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function() { // some heavy operation };
document.registerElement('x-foo', {prototype: proto});

At some point later, I would love to reference the prototype with something like:

// wish
var XFoo = document.getElementDefinition('x-foo');

But instead the only way I've come up with is:

// reality
var XFoo = document.createElement('x-foo').__proto__;

This is especially problematic when trying to write tests against heavy components - as there's no way to stub out the heavy behavior (with something like XFoo.createdCallback = // stub; before the original method is actually called.

2

There are 2 best solutions below

0
On

there's no way to stub out the heavy behavior

Use a function reference rather than an anonymous function:

proto.createdCallback = model.foo;

define it:

var model = {};
model.foo = function(){/*some heavy operation*/};

then stub it by redefining it:

var XModel = {};
XModel.foo = function(){/*stub*/};

and reference it in the test:

XFoo.createdCallback = XModel.foo;

References

0
On

If you have reference to the constructor of the custom element, you can use it to access the prototype.

var XFoo = document.registerElement('x-foo', {prototype: proto});
XFoo.prototype // this will give u access to the prototype object.