Skip to content

Instantly share code, notes, and snippets.

@roneesh
Last active May 26, 2016 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roneesh/a082c84e09c4a0c47c46 to your computer and use it in GitHub Desktop.
Save roneesh/a082c84e09c4a0c47c46 to your computer and use it in GitHub Desktop.
Front-end framework using object.observe! (just the JS)
var person = {
name: 'Dude!',
age: '100',
profession :'Welder'
},
hook = document.getElementById('hookOne');
function render(location, object) {
location.innerHTML = '';
var newBio = document.createElement('div');
for (property in object) {
var newBioTag = document.createElement('p'),
newBioLine = document.createTextNode(property.toUpperCase() + ': ' + object[property])
newBioTag.setAttribute('data-objectProperty', property);
newBioTag.appendChild(newBioLine);
newBio.appendChild(newBioTag);
};
location.appendChild(newBio);
runListeners();
}
Object.observe(person, function(changes) {
render(hook, person);
// You could also do this for an external data source
// $.post(url, change)
// .then(render(hook, person))
// .fail( some undo change code that object.observe has... if it has , render(hook, person));
});
render(hook, person);
function runListeners() {
pTags = document.getElementsByTagName('p')
for (var i = 0; i < pTags.length; ++i) {
pTags[i].addEventListener('click', function() {
var inputTag = document.createElement('input');
objectAttribute = this.getAttribute('data-objectProperty');
inputTag.setAttribute('data-objectProperty',objectAttribute);
inputTag.setAttribute('placeholder',objectAttribute);
this.parentNode.replaceChild(inputTag, this);
inputTag.addEventListener('change', inputSubmit);
})
}
}
function inputSubmit() {
var property = this.getAttribute('data-objectProperty');
person[property] = this.value;
render(hook, person);
}
@roneesh
Copy link
Author

roneesh commented Mar 19, 2015

This is just a proof of concept that with Object.observe you have what could be a front-end framework. The render function was inspired by a a talk on React. Rather than update Dom elements it just clears it out and re-creates, but since that happens you have to run Listeners again. To make this work just load it in an HTML document that has a div with an id="hookOne" (and maybe style it nicely too). You would need to add code to get some data from an external API too.

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