JQuery - Saving js array and list of DOM objects in sync?

Say I have an array of objects

[{href: 'some_uri', 'class': 'this-css-class'}, {href: 'another_uri', 'class': 'that-css-class'}]

Now I want to map this to the 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> 

Suppose I add another object to my array, I want to add a new list <li> to the list. And vice versa, when I $('.that-css-class').remove() one of the elements of the list, I want it to also disappear in the array.

I would like to save it in jQuery, since I do not want to introduce another framework into the project.

Help with great gratitude, it was in my head. Thanks.

+6
source share
2 answers

Something like this ?: 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); 

Selection:

 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'); 
+1
source

I don't know what your specific use case is, but keeping your data in sync and browsing (i.e. the DOM) handles backbone.js very well

You can see the following sample application to see how Model, Collection, and View are used, so that the JSON data stored in localStorage is in sync with what is displayed to the user through the DOM

Demo and annotated source

But this is just part of the functions provided by backbone.js that can be built into one library, as you offer. I do not know any such library.

+2
source

Source: https://habr.com/ru/post/911923/


All Articles