Skip to content

Instantly share code, notes, and snippets.

@argyleink
Forked from paulirish/bling.js
Last active May 19, 2018 01:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save argyleink/6811428290ac41cab8d4dab94b9edf97 to your computer and use it in GitHub Desktop.
Save argyleink/6811428290ac41cab8d4dab94b9edf97 to your computer and use it in GitHub Desktop.
add some sugar to bling dot js
const sugar = {
on: function(names, fn) {
names
.split(' ')
.forEach(name =>
this.addEventListener(name, fn))
},
setAttributes: function(attrs) {
Object.entries(attrs)
.forEach(([key, val]) =>
this.setAttribute(key, val))
}
}
// shorthand querySelector: $('.foo') $('.child', context_node)
export const $ = (query, $context = document) =>
Object.assign($context.querySelector(query), sugar)
// shorthand querySelectorAll: $$('.foo') $$('.child', context_node)
export const $$ = (query, $context = document) =>
Object.assign(
[...$context.querySelectorAll(query)]
.map($el => Object.assign($el, sugar))
, {
on: function(names, fn) {
this.forEach($el => $el.on(names, fn))
},
setAttributes: function(attrs) {
this.forEach($el => $el.setAttributes(attrs))
}
})
@argyleink
Copy link
Author

argyleink commented Apr 1, 2018

some example test usage:

import { $, $$ } from './utilities/shorthands'

const main_btn   = $('button[primary]')
const btns       = $$('button')
const btnSpans   = $$('span', btns)

main_btn.on('click', e => console.log(e.target))
btns.on('click', e => console.info(e.target))

// use native array methods on the nodes: map, reduce, filter
btns.forEach(btn => console.warn(btn))

// watch multiple events
$('h1').on('click mouseover', ({target}) => console.log(target.textContent))

main_btn.setAttributes({
  test: 'foo',
  hi: 'bye',
})

btns.setAttributes({
  tests: 'foo',
  his: 'bye',
})

@argyleink
Copy link
Author

the above, with some other extras, is now available from npm https://www.npmjs.com/package/blingblingjs

npm i blingblingjs

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