Skip to content

Instantly share code, notes, and snippets.

@FLamparski
Created September 4, 2014 20:13
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FLamparski/1122e08edeef19ff0913 to your computer and use it in GitHub Desktop.
Save FLamparski/1122e08edeef19ff0913 to your computer and use it in GitHub Desktop.
Reactivity in vanilla JS? Yes you can!
<!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>
// 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
})
})
})
@athdromeda
Copy link

Note: Object.observe is deprecated

@slopesweb
Copy link

Note: Object.observe is deprecated

Alternative?

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