I implemented an event binding for the scroll
event on a DIV. To add debounce functionality to the handler, I created a function on my model that generates the debounced handler. Then, in my view, I bind this factory function.
I assumed that my factory function would create the debounced function and knockout would bind it to the event. However, it seems like knockout is recreating and invoking my debounced function every time the event is triggered, rendering the debounce ineffective.
This is how I structured my code:
<div data-bind="event.scroll: getScrollHandler()"></div>
In my model:
var viewModel = {
getScrollHandler: function(data, evt) {
return debounceFunction(function(data, evt) {
// perform necessary actions here...
});
}
};
I expected the getScrollHandler
method to be executed only once during the initial binding process, with the returned function being bound thereafter. Unfortunately, it appears that knockout is wrapping everything in a new function, causing it to execute on every scroll event.
I am curious about the inner workings of Knockout regarding this behavior.
UPDATE
Since I am utilizing TypeScript and the handler is a member method of a class, I am constrained to this type of function member assignment. Directly assigning the debounced function as a member proves to be more challenging (though not impossible).