Building Collections Efficiently Using jQuery
backbone.js however I wanted to present a simpler solution without the use of any frameworks.
We have some type of collection of common items that can be added or removed on the fly via AJAX calls and no page refreshes.
<div id="blurbs_table"></div> <div id="blurbs_table_items" style="display:none;"> <div class="item"> <div class="blurb">jQuery Rocks</div> <div class="menu"></div> </div> <div class="button view">view</div> <div class="button buy">buy</div> <div class="button info">info</div> <div class="button remove">remove</div> </div>
Here are a few assumptions we are going to make for this solution:
- The data we are receiving is in JSON format.
- Our items have dynamic components, for example the type of buttons in a menu (view, buy, sell, info, etc...)
- The real magic here happens with the jQuery clone() function allowing us to easily make copies of the components we need for our collection.
- We can use the loadItems() function to build our initial collection by just traversing through the list of items and appending them.
- Your functions that do things like add, remove or update would pretty much stay the same way. They make an AJAX call get back some kind of response that if successful performs some action. The important piece is the appendItem() function, here is where we build the items for our collection.
- This method is also particularly useful when you have many such collections similar to each other but with slight variations. It gives you maximum reusability but keeps things from getting confusing.
- This also keeps our CSS code clean as we can write the full rules for one complete collection and they are only applied if the items within it exist.