I’m following a tutorial here: http://blog.chariotsolutions.com/2012/01/from-list-to-details-view-using.html
I am trying to dynamically bind a click handler to a listview item as it is rendered. The method described in the link above does not work. I have tried several alternatives..
The tutorial suggests this in the render function: (template is below)
activities.each(function(activity){
var renderedItem = template(activity.toJSON()),
$renderedItem = $(renderedItem); //convert the html into an jQuery object
$renderedItem.jqmData('activityId', activity.get('id')); //set the data on it for use in the click event
$renderedItem.bind('click', function(){
//This part is different in tutorial, but irrelevant
alert("Hello.");
alert($(this).jqmData('activityId')); //'this' represents the element being clicked
});
listView.append($renderedItem);
});
This does not work. The buttons get created, but nothing happens when I click, and Chrome’s dev tools show only two click event listeners: document, and document
I have tried these as substitutes but nothing works. No alert message, no breakpoint hit, no registered click event listeners. …
$renderedItem.on('click', function(){
alert("Hello.");
alert($(this).jqmData('activityId')); //'this' represents the element being clicked
});
$renderedItem.live('click', function(){
alert("Hello.");
alert($(this).jqmData('activityId')); //'this' represents the element being clicked
});
I have also tried the standard Backbone way of registering events to no avail…
events: {
'click .activity-list-item':'btnSelected'
},
...
btnSelected: function(){
alert("Hello");
//This is what I really want. Some data attached to the sender
alert($(this).jqmData('activityId'));
}
This is template:
<li><a href="#activity-details" class="activity-list-item"identifier="<%= id %>"><%= date %> - <%= type %></a></li>
Thank you, ladies and gentlemen for your time.
EDIT: I have done a test and I think, for some reason, the bind is getting removed. I can do this:
myCollection.at(0).bind('click', function(){
alert("hello");
});
myCollection.at(0).trigger('click');
…and it works as it should. Is there a reason that the binds might be getting removed?
EDIT 2: This is still not solved. Unfortunately my temporary solution was exactly that. I can delete all listview items, repopulate, and refresh and still have clickability, but if I APPEND items to the list, they are not clickable. .bind, .on, .live, .delegate. None of them work. I really wish there was more documentation about this. This is a common programming problem with no common solution.
It looks like jquerymobile may be intercepting & unbinding your event bindings. This is still just a guess, since I’m not setup to test JQM apps right now, but it looks like there is a setting to turn off jqm’s default control of event bindings for links,
linkBindingEnabled.You can set it like this:
Try that, see if it gets you anywhere… If not, back to the drawing board 🙂