Let's say I have the following web-component:
<link rel="import" href="my-dialog.htm">
<my-dialog id='mydialog1' heading="A Dialog">Lorem ipsum</my-dialog>
See here for more info: http://cbateman.com/blog/a-no-nonsense-guide-to-web-components-part-1-the-specs/
and here: http://www.revillweb.com/tutorials/web-component-tutorial/
However, apart from attributes sometimes I'd like to initialize it with some object that has a bunch of properties for example:
var obj = { heading: 'hello there', data1: 123, name: 'blabla' };
//^^ this can be any type of data.. think some kind of data model here, and maybe I get this model from the server.
So I can't send the above object within my html via attributes, cause I might have alot of settings and/or I might get it at a later point from the server, so I need to do it in javascript.
So what I've been doing is I've just been taking the object after it has been created:
// initialize is a function I have inside my web component
$('#mydialog1').get(0).initialize(obj);
^^ And this works, initialize(..) is a function inside my web component.. But:
Question #1 I wonder if this is the correct way to initialize a web component, as it seems a bit messy.
Also, if one instantiates a web-component in code:
$('body').append("<my-dialog id='bla'></my-dialog>");
$('#bla').get(0).initialize(obj);
Question #2 Can I assume on the second line, that 'bla' has been created here with all its methods? (funny enough, this works but I thought maybe it'd be better to wait for some kind of event or something that the component is ready)
Because append has a synchronous(opposite of async) behavior, it will always work.
Do not litter your codebase with needless safety nets(events, polling...).
In short, right after .append is executed the element is present on DOM and you can query it with selectors and do whatever you want to do with it.
Like virtually all JavaScript methods, HTML appending is synchronous, which means that you can expect the correct DOM elements to be constructed when the function returns - if not so, the function would accept callbacks or return a Promise or similar. Thus, you can trust that the thing has been created and initialize it. And initializing it in this way is probably the best thing to do (though there might be a way to do it all in one line.)
If you feel the need to convince yourself that a given import method (anything that consults an external file) is synchronous rather than asynchronous, you can do the following on a *nix system:
yes
to it. ($ yes >pipe1
)yes
(an infinite series of y
s followed by linefeeds) syntactically correct for your situation.cat
) to it. ($ cat header.htm pipe1 >pipe2.htm
)<link rel="import" href="pipe2.htm">
or var x = require("pipe2.js")
)Does your UI hang? If so, then it's synchronous. Does it keep on going? Then it's asynchronous.
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