Skip to content

Instantly share code, notes, and snippets.

@ohidurbappy
Created September 10, 2022 18:28
Show Gist options
  • Save ohidurbappy/bca547b16e0a0ca307e256192408f4eb to your computer and use it in GitHub Desktop.
Save ohidurbappy/bca547b16e0a0ca307e256192408f4eb to your computer and use it in GitHub Desktop.
Javascript Reactivity without any framework
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NoFrameworkReactivity</title>
</head>
<body>
<header>
<h4>NoFrameworkReactivity</h4>
<p>
A proof of concept for a reactive frameworkless web app.
</p>
</header>
<div id="root">
</div>
<footer>
<p>
2022
</p>
</footer>
<script>
function BlogPost(postData) {
return `<div class="post">
<h1>${postData.title}</h1>
<h3>By ${postData.author}</h3>
<p>${postData.body}</p>
</div>`;
}
function BlogPostList(posts) {
return `<div class="blog-post-list">
${posts.map(post=>BlogPost(post)).join('')}
</div>`
}
var blog_posts=[
{
author: 'Author 1',
title: 'A JS Trick',
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
},
{
author: 'Author 2',
title: 'Another JS Trick',
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
},
{
author: 'Author 3',
title: 'Yet Another JS Trick',
body: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
}
]
function render() {
document.getElementById('root').innerHTML=BlogPostList(blog_posts);
}
function Reactive(){
let state = [];
Object.defineProperty(this, 'state', {
get: function() {
return state;
},
set: function(value) {
state = value;
render();
}
});
}
let reactive = new Reactive();
var $= document.querySelectorAll.bind(document);
document.addEventListener('DOMContentLoaded', function() {
reactive.state = blog_posts;
});
// every 2 seconds we add a dummy post to the array
setInterval(function(){
blog_posts=[{
"author": "Author "+Math.floor(Math.random()*100),
"title": "Yet Another JS Trick",
"body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
},...blog_posts];
reactive.state = blog_posts;
console.log("Added a new post");
}, 2000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment