Let's say I have an array of objects
[{href: 'some_uri', 'class': 'this-css-class'}, {href: 'another_uri', 'class': 'that-css-class'}]
I now want to map that to a html list:
<ul>
<li class="this-css-class"><a href="some_uri">some_uri</a></li>
<li class="that-css-class"><a href="another_uri">another_uri</a></li>
</ul>
Assume I add another object to my array, I want to have a new <li>
added to the list as well. Conversely, when I $('.that-css-class').remove()
one of the list items, I want it to be gone in the array as well.
I would like to keep it in jQuery, as I don't want to introduce another framework to the project.
Help greatly appreciated, this has been doing my head in. Thanks.
I don't know what your exact use case is but keeping your data and view(i.e. DOM) in sync is handled very well by backbone.js
You can see following example app to see how Model, Collection and View are used to keep JSON data stored in localStorage in sync with what is displayed to user through DOM
Demo and annotated source
But this is just a part of functionality provided by backbone.js which can be embedded in a single library as you are suggesting. I don't know of any such library though.
Something like that ? : http://jsfiddle.net/RZPNG/4/
var datas = [
{href: 'some_uri', 'class': 'this-css-class'},
{href: 'another_uri', 'class': 'that-css-class'}
],
ul = $('ul');
$.each(datas, function(key, value) { // initialize list
createElement(value);
});
function createElement(elem) {
ul.append($('<li class=' + elem.class + '><a href="' + elem.href + '">' + elem.href + '</a></li>'));
}
function addElement(elem) {
datas.push(elem);
createElement(elem);
}
function removeElement(i) {
datas.splice(i, 1);
$(ul.find('li').get(i)).remove();
}
addElement({href: 'foo', 'class': 'bar'});
removeElement(1);
Selector way :
var datas = [
{href: 'some_uri', 'class': 'this-css-class'},
{href: 'another_uri', 'class': 'that-css-class'}
],
ul = $('ul');
$.each(datas, function(key, value) { // initialize list
createElement(value);
});
function createElement(elem) {
ul.append($('<li class=' + elem.class + '><a href="' + elem.href + '">' + elem.href + '</a></li>'));
}
function addElement(elem) {
datas.push(elem);
createElement(elem);
}
function removeElement(selector) {
datas.splice(findElement(selector), 1);
$(ul.find('li.' + selector)).remove();
}
function findElement(selector) {
for (var i in datas) {
if (datas[i].class === selector) {
return i;
}
}
}
addElement({href: 'foo', 'class': 'bar'});
removeElement('that-css-class');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With