Created
September 4, 2014 20:13
-
-
Save FLamparski/1122e08edeef19ff0913 to your computer and use it in GitHub Desktop.
Reactivity in vanilla JS? Yes you can!
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Object.observe</title> | |
</head> | |
<body> | |
<h1 reactive>Title here</h1> | |
<p reactive>Text here</p> | |
<hr /> | |
<p><b>Hey!</b> Open up the console and change the <tt>title</tt> | |
and <tt>content</tt> attributes of <tt>myDataBinding</tt> to see | |
the values above react like magic!</p> | |
<script src="oo.js"></script> | |
</body> | |
</html> |
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
// Reactivity on the cheap? | |
// The aim here is to have a ReactJS (or even Meteor) type of databinding | |
// without using any external libraries of frameworks. You only get the | |
// window object and modern JS. | |
// First, let's help ourselves to a cheap, shoddy imitation of jQuery: | |
// querySelectorAll(selector) => NodeList | |
var µ = document.querySelectorAll.bind(document) | |
// Then, we wait until the DOM is actually available. This is analogous to | |
// $(function()...) | |
document.addEventListener('DOMContentLoaded', function(){ | |
console.log('We are ready') | |
// We cheat a little and define our data binding here. We will be | |
// modifying it from the console and see magic reactivity. | |
window.myDataBinding = { title: 'My title', content: 'My content' } | |
// Keep a reference to our heading and our paragraph | |
var theH1 = µ('h1[reactive]')[0] | |
var theP = µ('p[reactive]')[0] | |
// And this is where the magic happens. Object.observe will | |
// attach an event listener to any object (minus DOM stuff) | |
// and call a provided function with the changeset. Often, | |
// changesets will contain just one change but they don't | |
// have to. | |
Object.observe(window.myDataBinding, function (changeset) { | |
// We iterate through the list of changes... | |
changeset.forEach(function(change){ | |
// ...and update our heading and para accordingly. | |
theH1.innerText = change.object.title | |
theP.innerText = change.object.content | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
try: https://medium.com/@Mikepicker/unravel-reactivity-in-16-lines-of-vanilla-js-af13b185a733