Ad/iklan :







Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total post.pos : 13631+

[Go Make Things] Keeping state in the DOM vs. state in a JavaScript object

Yesterday, I shared my latest YouTube video on how to build a modern web app with vanilla Web Components.

If you missed it, the tl;dr is that users can add items to a list (ul) using a form. Then, they click a button to pick item from the list at random.

The code for picking the items looks like this…

/**   * Handle click event   * @param  {Event} event The event object   */  onclick (event) {    	// Get all of the list items  	let items = Array.from(this.list.querySelectorAll('li')).map(function (item) {  		return item.textContent;  	});    	// Randomize the items  	this.shuffle(items);    	// Show the result  	this.result.textContent = `You picked ${items[0]}`;    }  

One viewer asked a question:

Why not store the items as an array instead of getting them from the DOM each time?

It's a great question!

In most modern JS apps, you'd do something like this instead…

// Get an immutable copy of the items  let items = Array.from(this.items);    // Randomize the items  this.shuffle(items);    // Show the result  this.result.textContent = `You picked ${items[0]}`;  

But as Jeremy Keith wrote in his article on HTML Web Components

Try not to bring React's mindset with you…

Think about composibility with existing materials. Do you really need to invent an entirely new component from scratch? Or can you use HTML up until it reaches its limit and then enhance the markup?

Web Components are very much with the grain of the web.

Storing your data in JavaScript objects is a React convention. It absolutely makes sense in certain situations, but in this app, it would just add more complexity.

If my items were also kept an array, every time I add an item, I also need to update the array. If I delete an item, I need to go back to the array, find that item, and remove it.

It's simpler and less buggy to let the DOM be the state of the app, and query it when needed.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+
0 Komentar untuk "[Go Make Things] Keeping state in the DOM vs. state in a JavaScript object"

Back To Top