Created
May 7, 2016 17:13
-
-
Save thurt/b7ac60f95297ab00de2c252b7c3d14b5 to your computer and use it in GitHub Desktop.
A quick one-way data binder which will change the textContent of the nodes which have a data-key attribute when calling DataBind function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gets all html elements with data-key attribute and stores them in a dictonary. | |
// later, using DataBind function triggers a setter function for that key | |
// which applies the assigned value to the associated node.textContent | |
var DataBind = (() => { | |
// private member | |
var _binder = Array.from(document.querySelectorAll('[data-key]')) | |
.reduce((dict, node) => { | |
Object.defineProperty(dict, node.dataset.key, { | |
set(new_value) { | |
// node is in the closure | |
node.textContent = new_value | |
} | |
}) | |
return dict | |
}, {}) | |
// DataBind function | |
return (kv_pairs) => { | |
for (var [k, v] of kv_pairs.entries()) { | |
_binder[k] = v | |
} | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment