-
Notifications
You must be signed in to change notification settings - Fork 49
Common Patterns
Kyle Robinson Young edited this page Sep 14, 2016
·
6 revisions
An element that consists of an input field and button when pressed will return the value submitted.
var bel = require('bel')
module.exports = function (onsubmit) {
var input = bel`<input type="text" value="" />`
return bel`<form onsubmit=${function (e) {
e.preventDefault()
onsubmit(input.value)
}}>
<label>Your Name:</label>
${input}
<button type="submit">submit</button>
</form>`
}
There are times you need to know when your element has been inserted or removed from the DOM. Such as when attaching outside event handlers. The onload
and onunload
events are special events available to bel
elements:
var bel = require('bel')
var morphdom = require('morphdom')
var modal = render(true)
function render (opened) {
if (!opened) return ''
return bel`<div class="modal" onload=${function () {
document.addEventListener('mousedown', clickedOutsideModal)
}} onunload=${function () {
document.removeEventListener('mousedown', clickedOutsideModal)
}}>Hello!</div>`
}
function clickedOutsideModal () {
morphdom.update(element, render(false))
}
The above example opens a modal/popover/contextmenu and then we can check if a click occurs outside of the element to know when to hide the modal.