Skip to content

Instantly share code, notes, and snippets.

@geekpulp
Last active July 2, 2021 11:01
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 geekpulp/53e2acff18f7e2f2f657c3585edca709 to your computer and use it in GitHub Desktop.
Save geekpulp/53e2acff18f7e2f2f657c3585edca709 to your computer and use it in GitHub Desktop.
Data Reactivity with Vanilla JS
<div id="app"></div>
// The data object (or state)
var data = {
listName: 'Starting at Hogwarts',
todos: []
};
// The state-based UI
var template = (data) => {
// Create the list heading
var html = '<h1>' + data.listName + '</h1>';
// If there are no list items, show a message
// Otherwise, display the list items
if (data.todos.length < 1) {
html += '<p><em>You do not have any items to complete yet. Please add some.</em></p>';
} else {
html += '<ul>' + data.todos.map(function (todo) {
return '<li>' + todo + '</li>';
}).join('') + '</ul>';
}
// Return the template
return html;
};
/**
* Reactivity update the data object
* @param {Object} obj The data to update
*/
var setData = (obj) => {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
data[key] = obj[key];
}
}
app.innerHTML = template(data);
};
// Render the initial UI
var app = document.querySelector('#app');
app.innerHTML = template(data);
// Uncomment this to update the UI
// You can also open up the console feature and run it there
/*
setData({todos: [
'Fix my wand',
'Buy new robes',
'Enroll in courses'
]});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment