Can I get usable data in a jQuery live handler for a custom event?
-
19-09-2019 - |
Question
jQuery now allows you to use live to handle custom events, something I've used in my latest project and found very handy. I have come up against a limitation/bug, however, that I'm hoping someone will be able to help me with.
When you trigger an event, you can pass additional array of data too, like this:
$(this).trigger('custom', ['foo', 'bar' ]);
If you were just using bind, you could absolutely access these variables. However, if you're using live, it turns out that you have no access to data as far as I can tell. Am I wrong? Is there another way?
Here is some demo code to illustrate:
$().ready(function() {
$('button').click(function(){
$('<li>Totally new one</li>').appendTo('ul');
});
$('li').bind('custom', function(e, data) {
// this one works fine for old elements, but not for new ones
$('#output1').text('Bind custom from #' + e.target.id + '; ' + data);
}).live('custom', function(e, data) {
// this one triggers for old and new elements, but data is useless
$('#output2').text('Live custom from #' + e.target.id + '; ' + data);
}).live('click', function(){
$('div').text('');
// just using click count to illustrate passing data in the trigger
var clicks = $(this).data('clicks');
if(typeof clicks == 'undefined') clicks = 1;
$(this).trigger('custom', ['Times clicked: ' + clicks ]).data('clicks', clicks + 1);
});
});
And the related HTML:
<button>Add</button>
<ul>
<li id="one">First Item</li>
<li id="two">Second Item</li>
<li id="three">Third Item</li>
</ul>
<div id="output1">Result 1</div>
<div id="output2">Result 2</div>
Solution
It looks like the easiest approach may be to use the format described in the last "alternate" example at http://docs.jquery.com/Events/trigger#eventdata. The example uses an object literal to specify the event object, in which you can create custom properties. I also tried the approach you described above to no avail, but the alternate format works for me. So instead of calling
$(this).trigger('custom', ['Times clicked: ' + clicks ])
try
$(this).trigger({type:'custom', clicks: clicks});
and then reference it in the event handler of your "custom" event via:
"Times clicked: " + e.clicks;
Hope that helps!