- From: Andrea Giammarchi <notifications@github.com>
- Date: Wed, 28 Jul 2021 02:53:59 -0700
- To: WICG/webcomponents <webcomponents@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <WICG/webcomponents/issues/509/888174728@github.com>
@andregs `has` requires inevitably a registry, so it'll mine the flexibility of the `ElementObserver`, but it's still possible.
```js
customBehaviors.define(
'my-thing',
{
observedAttributes: ['some', 'attribute'],
attributeChangedCallback(element, name, oldValue, newValue) {},
connectedCallback(element) {},
disconnectedCallback(element) {}
}
);
```
The `customBehaviors` will verify that `my-thing` wasn't previously defined, and then it'll do something like this:
```js
const registry = new Map;
customBehaviors.define = (name, behavior) => {
if (registry.has(name))
throw new Error(`duplicated ${name}`);
registry.set(name, {
instance: new ElementObserver(behavior),
options: {
attributes: true,
attributeFilter: behavior.observedAttributes || [],
attributeOldValue: true
}
});
};
// a simulation of what should happen at the global level
const mo = new MutationObserver(records => {
for (const {target, attributeName, oldValue} of records) {
if (attributeName === 'has') {
const newBehaviors = (target.getAttribute('has') || '').split(/\s+/);
const oldBhaviors = (oldValue || '').split(/\s+/);
for (const behavior of oldBhaviors) {
if (customBehaviors.has(behavior) && !newBehaviors.includes(behavior))
customBehaviors.get(behavior).instance.disconnect(target);
}
for (const behavior of newBehaviors) {
if (customBehaviors.has(behavior) && !oldBhaviors.includes(behavior)) {
const {instance, options} = customBehaviors.get(behavior);
instance.observe(target, options);
}
}
}
}
});
mo.observe(document, {
attributeFilter: ['has'],
subtree: true
});
```
The only possible improvement I can see needed is an `eo.isObserving(target)` to avoid missing new defined behaviors already set as attribute.
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/509#issuecomment-888174728
Received on Wednesday, 28 July 2021 09:54:12 UTC