jquery datatables multiple calls to event handler with live function

时光怂恿深爱的人放手 提交于 2019-12-06 06:12:42

Have had this issue with live and ajax. What I wound up doing is I re-registered the event clicks upon receiving an ajax response. Without an example, it's hard to recommend a solution but the idea is to attach the click events on page load using bind/click (for the default/initial display) and then re-register the click events again on a successful ajax response. Of course, placing the event-binding code in a reusable component such as a function so it can be easily called.

Rohit Banga

Fixed the problem

The issue was I could not just register for click event on elements within the datatable rows. The events would not be registered across datatable pages.

Using live() to register the events helped and on page change the events would be registered automatically.

But for my usecase that led to another problem every time I did a search, I would replace the datatable with a new one. The new datatable would register for those events again. So that meant multiple handlers being invoked for the same element. Because the live() function was called twice on the same class and jquery is not expected to compare whether two callback handlers are the same.

I veered in a different direction and tried to register click events using .click() in place of .live() on page change using the page event (http://datatables.net/docs/DataTables/1.9.beta.1/#page_details). This did not help since the events the page change event was invoked before the contents were refreshed with the events on the new page.

I also tried using click() instead of live() and binding click only if it had not already been registered using the example given here https://stackoverflow.com/a/6361507/161628. This technique worked across table replace but not across multiple pages.

Ultimately I found the .die() function. I invoke it before I call the live() function. The call to live() ensures that event handlers are registered on page change while the call to die() ensures I unregister live() events made previously on elements of that class. I avoid multiple calls to live() function this way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!