jQuery now allows you to use live to handle custom events, which I used in my last project and found very convenient, However, I came across a limitation / error that I hope someone can help me with.
When you raise an event, you can pass in an additional data array, for example:
$(this).trigger('custom', ['foo', 'bar' ]);
If you just used bind , you could absolutely access these variables. However, if you use live, it turns out that you do not have access to the data , as far as I can tell . Am I mistaken? Is there another way?
Here is an example demo code:
$().ready(function() {
$('button').click(function(){
$('<li>Totally new one</li>').appendTo('ul');
});
$('li').bind('custom', function(e, data) {
$('#output1').text('Bind custom from #' + e.target.id + '; ' + data);
}).live('custom', function(e, data) {
$('#output2').text('Live custom from #' + e.target.id + '; ' + data);
}).live('click', function(){
$('div').text('');
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>