Can I get usable data in jQuery live handler for custom event?

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) {
        // 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>
+3
1

, , "" http://docs.jquery.com/Events/trigger#eventdata. , . , .

$(this).trigger('custom', ['Times clicked: ' + clicks ])

$(this).trigger({type:'custom', clicks: clicks});

"" :

"Times clicked: " + e.clicks;

, !

+2

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


All Articles