Reputation: 380
Each one that managed to make an ajax function within a grid row; that is, from a button or a link of a certain cell. This works well. However, after the grid is updated using Ajax; Either to sort or filter; These functions are no longer executed. I have been observing this problem since Yii 1.x. The same happens to third-party libraries such as kartik \ editColumn. They only work the first time, after the Grid "reloads", they no longer work. It's wrong?
Upvotes: 0
Views: 50
Reputation: 6144
When you are binding the JS functionality to those links you bind them to elements in DOM that are present in the moment you do the binding. That's usually when the DOM has been build during page load.
After your ajax request is completed those elements with bound JS functionality are replaced with the new elements, but the JS functionality is not bound to those new elements. That's why the JS "stops" working after update.
There are two options how to deal with this.
1) Rebind the JS functionality after replacing the content.
You can put the binding to some function then call that function when page is ready and after you've replaced the html content.
2) Use event bubbling.
Most events are not just invoked on the element where they happen. They are also invoked on all their ancestors through the whole DOM. So you can bind the event not directly to the <a>
element but to some ancestor that won't be replaced with update. Using jquery you can do that easily using on(event, selector, handler)
like this:
$('.replace').click(function() {
$('.clickme1').replaceWith('<a href="#" class="clickme1">Replaced - 1</a>');
$('.clickme2').replaceWith('<a href="#" class="clickme2">Replaced - 2</a>');
});
//this is usual binding
$('.clickme1').click(function(event) {
alert('clickme1 clicked');
event.preventDefault();
});
//this uses bubbling
$('.wrapper').on('click', '.clickme2', function() {
alert('clickme2 clicked');
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<a href="#" class="clickme1">Click me - 1</a><br>
<a href="#" class="clickme2">Click me - 2</a>
</div>
<br>
<a href="#" class="replace">Replace links</a>
Upvotes: 1