A Pen by Chris Ferdinandi on CodePen.
Last active
July 2, 2021 11:01
-
-
Save geekpulp/53e2acff18f7e2f2f657c3585edca709 to your computer and use it in GitHub Desktop.
Data Reactivity with Vanilla JS
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
<div id="app"></div> |
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
// 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