Skip to content

Instantly share code, notes, and snippets.

@argyleink argyleink/blingbling.js forked from paulirish/bling.js
Last active May 19, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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

This comment has been minimized.

Copy link
Owner Author

argyleink commented Apr 12, 2018

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
You can’t perform that action at this time.