Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: adding ability to emit custom events #54

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,60 @@ FullName.propTypes = {
register(FullName, 'full-name');
```

### Custom Events

If you want to be able to emit custom events from your web component then you can add a `customEvents` object to the options.
Alternatively they can be supplied on the component. The events will be added to the props. They are async (Promise) methods
that the outside can respond to via a callback. Whatever you pass in to the method will be the `payload` in the event detail.

```js
function MyAsyncComponent({ onError, onLoaded, src }) {
const [posts, setPosts] = useState(null);

useEffect(() => {
if (!src) return;
axios.get(src).then(res => {
setPosts(res.data);
onLoaded(`Loaded ${res.data.length} posts`)
.then(res => {
console.log('got ack from host, do something...', res);
});
}, onError);
}, [src]);

return (
<div>
{ posts ?
posts.map(post => <Post key={post.id} data={post} />) :
<span>Loading...</span>
}
</div>
);
}
register(MyAsyncComponent, 'x-my-async', ['src'], {
customEvents: { onLoaded: 'loaded', onError: 'error' }
});
```

Later in the consuming HTML page:

```html
<x-my-async id="my1"></x-my-async>
<script>
const el = document.querySelector('#my1');
el.addEventListener('loaded', (e) => {
const { payload, callback } = e.detail;
console.log(payload);
// Loaded xx posts
callback('ok got it');
});
el.addEventListener('error', (e) => {
const { payload } = e.detail;
console.error('oh no failed to load posts');
});
el.setAttribute('src', 'https://jsonplaceholder.typicode.com/posts');
</script>
```

## Related

Expand Down
39 changes: 38 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,32 @@ export default function register(Component, tagName, propNames, options) {
inst._vdomComponent = Component;
inst._root =
options && options.shadow ? inst.attachShadow({ mode: 'open' }) : inst;

inst._customEvents = {};
const customEvents =
(options && options.customEvents) || Component.customEvents;
if (customEvents) {
Object.keys(customEvents).forEach((eventName) => {
const emitName = customEvents[eventName] || eventName;
const handler = (payload) => inst.dispatch(emitName, payload);
// later to propagate to props
inst._customEvents[eventName] = handler;
Object.defineProperty(inst, eventName, {
get() {
return handler;
},
});
});
}

return inst;
}
PreactElement.prototype = Object.create(HTMLElement.prototype);
PreactElement.prototype.constructor = PreactElement;
PreactElement.prototype.connectedCallback = connectedCallback;
PreactElement.prototype.attributeChangedCallback = attributeChangedCallback;
PreactElement.prototype.disconnectedCallback = disconnectedCallback;
PreactElement.prototype.dispatch = dispatch;

propNames =
propNames ||
Expand Down Expand Up @@ -78,7 +97,7 @@ function connectedCallback() {

this._vdom = h(
ContextProvider,
{ ...this._props, context },
{ ...this._props, ...this._customEvents, context },
toVdom(this, this._vdomComponent)
);
(this.hasAttribute('hydrate') ? hydrate : render)(this._vdom, this._root);
Expand Down Expand Up @@ -161,3 +180,21 @@ function toVdom(element, nodeName) {
const wrappedChildren = nodeName ? h(Slot, null, children) : children;
return h(nodeName || element.nodeName.toLowerCase(), props, wrappedChildren);
}

function dispatch(eventName, payload) {
return new Promise((resolve, reject) => {
const callback = (result, error) => {
if (error !== undefined) {
reject(error);
return;
}
resolve(result);
};
this.dispatchEvent(
new CustomEvent(eventName, {
bubbles: true,
detail: { callback, payload },
})
);
});
}
112 changes: 112 additions & 0 deletions src/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,118 @@ describe('web components', () => {
});
});

describe('Custom Events', () => {
function DummyEvented({ onMyEvent, onMyEventSuccess, onMyEventFailed }) {
function clickHandler() {
onMyEvent('payload').then(onMyEventSuccess, onMyEventFailed);
}
return (
<div>
<button onClick={clickHandler}>click</button>
</div>
);
}
const onMyEvent = 'myEvent';
const onMyEventSuccess = 'myEventSuccess';
const onMyEventFailed = 'myEventFailed';
DummyEvented.customEvents = {
onMyEvent,
onMyEventSuccess,
onMyEventFailed,
};
registerElement(DummyEvented, 'x-dummy-evented', [], {
customEvents: { onMyEvent, onMyEventSuccess, onMyEventFailed },
});

registerElement(DummyEvented, 'x-dummy-evented1');

it('should allow you to expose custom events', async () => {
let done;
const promise = new Promise((resolve) => {
done = resolve;
});
const el = document.createElement('x-dummy-evented');
root.appendChild(el);

el.addEventListener(onMyEvent, (e) => {
assert.equal(e.detail.payload, 'payload');
done();
});

act(() => {
el.querySelector('button').click();
return promise;
});
});

it('should enable async events (resolved)', async () => {
let done;
const promise = new Promise((resolve) => {
done = resolve;
});
const el = document.createElement('x-dummy-evented');
root.appendChild(el);

el.addEventListener(onMyEvent, (e) => {
const callback = e.detail.callback;
callback('success');
});

el.addEventListener(onMyEventSuccess, (e) => {
assert.equal(e.detail.payload, 'success');
done();
});

act(() => {
el.querySelector('button').click();
return promise;
});
});

it('should enable async events (rejected)', async () => {
let done;
const promise = new Promise((resolve) => {
done = resolve;
});
const el = document.createElement('x-dummy-evented');
root.appendChild(el);

el.addEventListener(onMyEvent, (e) => {
const callback = e.detail.callback;
callback(null, 'failed!');
});

el.addEventListener(onMyEventFailed, (e) => {
assert.equal(e.detail.payload, 'failed!');
done();
});

act(() => {
el.querySelector('button').click();
return promise;
});
});

it('should allow you to expose custom events via the static property', async () => {
let done;
const promise = new Promise((resolve) => {
done = resolve;
});
const el = document.createElement('x-dummy-evented1');
root.appendChild(el);

el.addEventListener(onMyEvent, (e) => {
assert.equal(e.detail.payload, 'payload');
done();
});

act(() => {
el.querySelector('button').click();
return promise;
});
});
});

function Foo({ text, children }) {
return (
<span class="wrapper">
Expand Down