Skip to content

Instantly share code, notes, and snippets.

@davidbgk
Last active February 2, 2016 17:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbgk/62c3aed0d09599ed0886 to your computer and use it in GitHub Desktop.
Save davidbgk/62c3aed0d09599ed0886 to your computer and use it in GitHub Desktop.
A new version of my custom shorteners for recent browsers.
<!doctype html>
<meta charset="utf-8">
<title>Test JavaScript</title>
<style>
.turn-red { color: red; }
.turn-green { color: green; }
.turn-blue { color: blue; }
</style>
<h1>red</h1>
<h1>green</h1>
<h1>blue</h1>
<ul>
<li><a href="">Item #1</a></li>
<li><a href="">Item #2</a></li>
<li><a href="">Item #3</a></li>
<li>Item #4</li>
</ul>
<script>
/* myquery - Abstration budget: 25 lines.
Inspired by https://github.com/remy/min.js and
https://gist.github.com/paulirish/12fb951a8b893a454b32
Adds `$` for selections, `$$` for single selection and
`on` + `trigger` for event handling (see `tests` below).
*/
window.$ = selector => Array.from(document.querySelectorAll(selector))
window.$$ = document.querySelector.bind(document)
window.on = Node.prototype.on = Array.prototype.on = function(type, ...rest) {
let listener
if (typeof rest[0] === 'function') {
listener = rest[0]
} else {
const [targetNodeName, innerListener] = rest
listener = function(event) {
if (event.target.nodeName.toLowerCase() === targetNodeName) {
innerListener(event)
}
}
}
Array.concat(this).forEach(element => element.addEventListener(type, listener))
}
window.$.on = window.on.bind(document)
window.trigger = Node.prototype.trigger = function(type, detail) {
const event = new CustomEvent(type, { detail: detail })
this.dispatchEvent(event)
}
Array.prototype.trigger = function(type, detail) {
this.forEach(element => element.trigger(type, detail))
}
window.$.trigger = window.trigger.bind(document)
/* /myquery */
/* Usage */
function tests() {
// Attaching/passing events for all titles.
$('h1').on('changeColor', event => {
console.log('changeColor received', event.detail)
event.target.classList.add(`turn-${event.detail.color}`)
})
$('h1').on('click', event => {
// Intentionally overcomplicated :-).
console.log('changeColor triggered', event.target)
event.target.trigger('changeColor', {color: event.target.innerHTML})
})
// Event delegation for a single item (works with many too).
$$('ul').on('click', 'a', event => {
event.preventDefault()
console.log(event.target.innerHTML)
})
// Anonymous pub/sub.
$.on('anonymousEvent', event => {
console.log('anoynmous event received')
})
$.trigger('anonymousEvent')
}
on('DOMContentLoaded', tests);
</script>
@davidbgk
Copy link
Author

davidbgk commented Feb 2, 2016

If you need more http://blissfuljs.com/ is probably the way to go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment