Created
May 31, 2018 23:41
-
-
Save dmamills/9d7251918158ca9aefa1a389c9397cce to your computer and use it in GitHub Desktop.
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
var obs = Observable(5); | |
var i = 0; | |
function observableEl(obs, numToListen) { | |
var el = document.createTextNode(`Listen count: ${numToListen} currentVal: ${obs()}`); | |
var remove = obs(function listener(val) { | |
el.textContent = `Listen count: ${numToListen} currentVal: ${val}`; | |
if(i >= numToListen) { | |
el.textContent = `Listen count: ${numToListen} unsubscribed`; | |
remove(); | |
} | |
}); | |
return el; | |
} | |
var rootEl = document.createElement('div'); | |
document.body.appendChild(rootEl); | |
for(let j = 5; j < 10;j++) { | |
var obsEl = observableEl(obs, j); | |
rootEl.appendChild(obsEl); | |
rootEl.appendChild(document.createElement('br')); | |
} | |
setInterval(_ => { | |
i++; | |
obs.set(Math.random() * 100); | |
}, 1000); |
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
<html> | |
<head> | |
<title>lol</title> | |
</head> | |
<body> | |
<h1>Observable Example</h1> | |
<script type="text/javascript" src="/index.js"></script> | |
<script type="text/javascript" src="/example.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
function Observable(val) { | |
var listeners = []; | |
observe.set = function(nv) { | |
val = nv; | |
listeners.forEach(function(l) { | |
l(val); | |
}); | |
} | |
return observe; | |
function observe(fn) { | |
if(!fn) { | |
return val; | |
} | |
listeners.push(fn); | |
return function remove() { | |
for(let i =0; i < listeners.length; i++) { | |
if(listeners[i] === fn) { | |
listeners.splice(i, 1); | |
console.log(listeners); | |
break; | |
} | |
} | |
} | |
} | |
} | |
window.Observable = Observable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment