Unbind jquery data.events from knockout elements

750 views Asked by At

I have a number of div elements in my page rendered using knockout variable to control how many divs are shown per page. When the page is initially rendered I set the value of this to 5 and bind mouseout event to each of the div using jquery hoverintent plugin. When a user clicks on Show more link I set the value of the max div t o10 and now 10 div elements are shown but only first 5 have the mouseout event binding. If I call the bind call again now the first 5 elements have 2 events attached to them. I can see the number of events using

$("div.ratingbig").data('events').mouseout

My question is how to remove the original binding before attaching the events again. Or is there a way to attach events for only new elements.

2

There are 2 answers

0
Sofia Khwaja On

I added the following statements to remove existing hoverIntent from div elements if it existed before adding it which will insert mouseout events

       if( $(this).hoverIntent != undefined){
            $(this).unbind("mouseenter").unbind("mouseleave")
            $(this).removeProp("hoverIntent_t");
            $(this).removeProp("hoverIntent_s");
        }
        $(this).hoverIntent(configObject);

Therefore each time before adding hoverintent it will check if the event already existed and if it did, it will be deleted first. Now I can call the above after changing the value of knockout variable and all elements get the hoverIntent.

2
ScottGuymer On

to remove the bindings you will need to calll the jquery off on the elements something like

$("div.ratingbig").off('mouseout')

the reason your new divs dont have the mouseover event on them is that they have no knowledge of it

You could use jquery deferred event handlers for this purpose. this will bind a new event whenever a div is added.

put a containing element around your generated divs with a class like container then run something like this on it Event binding

$('div.container').on('mouseout','div.ratingbig',function(){})

this will mean every div.ratingbing inside div.container will get the call back defined when the event happens.

Alternatively you could use the knockout Event Binding to bind an event with each of the divs.

Something like

<div data-bind="foreach: listOfDivs">
    <div class="ratingbig" data-bind="event: {mouseover: $root.someJsFunctionOnYourModel}"></div
</div>

the first example in the link shows you pretty much how to do it.