// This code uses ES2015.
// Please use a compatible browser like: Chrome, Opera, Firefox
function Seer (dataObj) {
let signals = {}
observeData(dataObj)
return {
data: dataObj,
observe,
notify
}
function observe (property, signalHandler) {
if(!signals[property]) signals[property] = []
signals[property].push(signalHandler)
}
function notify (signal) {
if(!signals[signal] || signals[signal].length < 1) return
signals[signal].forEach((signalHandler) => signalHandler())
}
function makeReactive (obj, key) {
let val = obj[key]
Object.defineProperty(obj, key, {
get () {
return val
},
set (newVal) {
val = newVal
notify(key)
}
})
}
function observeData (obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
makeReactive(obj, key)
}
}
// We can safely parse the DOM looking for bindings after we converted the dataObject.
parseDOM(document.body, obj)
}
function syncNode (node, observable, property) {
node.textContent = observable[property]
// We remove the `Seer.` as it is now available for us in our scope.
observe(property, () => node.textContent = observable[property])
}
function parseDOM (node, observable) {
const nodes = document.querySelectorAll('[s-text]')
for (const node of nodes) {
syncNode(node, observable, node.attributes['s-text'].value)
}
}
}
const App = Seer({
title: 'Game of Thrones',
firstName: 'Jon',
lastName: 'Snow',
age: 25
})
function updateText (property, e) {
App.data[property] = e.target.value
}
function resetTitle () {
App.data.title = "Game of Thrones"
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.