Binding Click Events to Dynamically Created ListView?
I have a ListView that requires a click event. When I first initialize the list, everything works great. As I rebuild the list (as items are added, edited, and removed), the click event stops working.
I have this HTML:
- <ul data-role="listview" data-theme="b" id="data-list" data-filter="true"></ul>
I have this code in an init function that gets called on page load:
- // initialize listview
- if (window.localStorage.length - 1) {
- var contacts_list = [], i, key;
- for (i = 0; i < window.localStorage.length; i++) {
- key = window.localStorage.key(i);
- if (/Contacts:\d+/.test(key)) {
- contacts_list.push(JSON.parse(window.localStorage.getItem(key)));
- } // if
- } //for
-
- if (contacts_list.length) {
- contacts_list
- .sort(function(a, b) {
- return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
- })
- .forEach(Contacts.tableAdd);
- $('#data-list').listview('refresh');
- } //if
- }; //if
Here's what the tableAdd function called on line 16 does:
- tableAdd: function(entry) {
- var key;
- var textToInsert = '<li data-icon="arrow-r" id=entry-'+ entry.id + '>';
- textToInsert += entry.last_name + ", " + entry.first_name + '<a href="#"></a></li>';
- $('#data-list').append(textToInsert);
- $("li#entry-" + entry.id).bind('click', function (e,info) {
- //$.mobile.pageLoading();
- Contacts.$form.first_name.value = entry.first_name;
- Contacts.$form.last_name.value = entry.last_name;
- Contacts.$form.email.value = entry.email;
- Contacts.$form.id_entry.value = entry.id;
- $('#delete-button-area').show();
- $.mobile.changePage("form-page", "slide", false, true);
- });
- }, // end tableAdd
So far, that works well for me....
As I add and remove list elements localStorage using other areas of code, I want to rebuild the list element, so I do this...
- refreshTable: function() {
- // remove all rows
- $('#data-list').empty();
- // initialize listview
- if (window.localStorage.length - 1) {
- var contacts_list = [], i, key;
- for (i = 0; i < window.localStorage.length; i++) {
- key = window.localStorage.key(i);
- if (/Contacts:\d+/.test(key)) {
- contacts_list.push(JSON.parse(window.localStorage.getItem(key)));
- } // if
- } //for
-
- if (contacts_list.length) {
- contacts_list
- .sort(function(a, b) {
- return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
- })
- .forEach(Contacts.tableAdd);
- $('#data-list').listview('refresh');
- } //if
- }; //if
All of the code below line 3, $('#data-list').empty();, is identical to the code that gets called when the page initializes.
The listview looks great, but the click event is not being bound to the entry.