A simple way to integrate jquery with native web-components
Download: 1.2.1
CDN (JSDELIVR) 1.2.1 1.2.1-minified
$wc()
.template('<p>')
.onCreate(function () { this.hello = "Hello World"; })
.connectedCallback(function ($host) { $host.find('p').text(this.hello); })
.attributeChangedCallback(($host, changed) => {
if(changed.name === 'color'){
$host.find('p').css('color', changed.newValue);
}
}, ['color'])
.extend({
changeMessage: async function (newMessage) {
const $host = await this.$host;
$host.find('p').text(`"${this.hello}" changed with "${newMessage}"`);
}
})
.define('fluent-component');$(document).ready(() => {
$('button[is=fancy-button]').click(() => {
$('fluent-component').changeMessage("Hello universe!");
});
$('#btn-color').click(() => {
const randomColor = Math.floor(Math.random()*16777215).toString(16);
$('fluent-component').attr('color', '#'+randomColor);
});
});For callbacks, arrow or anon functions can be used. Use anon functions if you want to access
the webcomponent's scope, besides $host provided as arg.
In the above example see how this.hello is available in any callback. (this would not be possible if
callback was arrow). But of course if only $host is needed, one can use just arrow instead.
The functions provided to extend object argument shouldn't be arrows. These are attached to webcomponent's prototype. See above how we access changeMessage.
Extending native html elements with fluent builder is simple:
$wc(HTMLButtonElement).define('fluent-button', 'button');- template - could be a html string or a template id
- templateSources - array of paths of template html or css files. (this has precedence over
templatemethod) - extend - object of methods that will attached to the web-component.
- lifecycle web-components methods:
- onCreate - called on web-component creation
- connectedCallback - called when wc is connected with a
$host(the shadowRoot host) arg. - disconnecteCallback - called when wc is disconnected
- attributeChangedCallback - one must provide the callback, and an array of observed attributes.
When attr has changed callack is called with $host, and a
changedobject containing attrname,oldValue, andnewValue
- define - terminal method that will define the component; it takes the name and, as optional, the html element tag name.
- getting the
shadowRoot$('fluent-component').$shr()
- getting the shadowRoot
host:Note that this returns a promise because the template might be loaded asynchronous withconst $host = await $('fluent-component').$host(); $host.find('p').css('outline', '1px solid red');
templateSources - query a slot:
//... const slot = $host.slot('slot[name=my-slot]')
- placing an element into a slot:
//.. const div = $host.slot($('<div>'), "my-slot");
- getting a method cretead with
extend//.. $('fluent-component').changeMessage("Hello universe!");