Zoltán Tamási
Zoltán Tamási

Reputation: 12764

Knockout event binding unexpected behaviour

I have an event binding for the scroll event on a DIV. For debouncing the handler I introduced a function on my model which creates the debounced handler, and I'm binding this factory function in my view.

I would expect that my factory creates the debounced function and knockout will bind that to the event. Instead, it seems like knockout recreates and calls my debounced function at every event trigger, so debouncing doesn't work at all.

My view

<div data-bind="event.scroll: getScrollHandler()"></div>

My model

var viewModel = {
  getScrollHandler: function(data, evt) {
    return debounceFunction(function(data, evt) {
      // dp the actual handling...
    });
  }
};

I would expect that the getScrollHandler method would execute only once at binding initialization time, and it would bind the returned function.

Instead, it seems like knockout is wrapping it all to a new function so it runs on every scroll event.

How exactly does it work in Knockout?

UPDATE

As I'm using TypeScript and this handler is a member method of a class, I'm limited to this kind of function member assignment, I cannot directly assign the debounced function as a member (or actually I could, but in some uglier way only).

Upvotes: 0

Views: 100

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

Assuming you have an implementation similar to this one, the idea is it creates a new function which you then use in place of your original function. Try changing your code to this:

getScrollHandler: debounceFunction(function(data, event) { 
  ...
})

This will create the function once and re-use it every time the scroll is activated.

Upvotes: 1

Related Questions