I would like my throttle as a dynamic number that I can change at will, however it doesn't seem possible. Is this a limitation of the throttle extender?

In my case I have a grid filter that I'm throttling. If I have only a few items in the grid, I would like a very low throttle. However if the grid row count gets very large I would like to change it (perhaps to a max of ~300ms). e.g.:

this.filter = ko.observable("").extend({ throttle: 1 });

then later I would like to do something like:

this.filter.extend.throttle = 300;
有帮助吗?

解决方案

That won't work for the built-in throttle method.

It's not hard to build this yourself. For example, here's some code that will allow you to call .throttle on any observable, passing an a throttle time observable which can be changed at will:

ko.subscribable.fn.throttle = function(throttleTimeObservable) {
    var subscribable = this;
    var throttledObservable = ko.observable();
    var timeoutHandle = null;

    if (ko.isObservable(throttleTimeObservable)) {
       throttletimeObservable.subscribe(function() { clearTimeout(timeoutHandle) });
    }

    subscribable.subscribe(function(val) {
        clearTimeout(timeoutHandle);
        throttleTime = ko.utils.unwrapObservable(throttleTimeObservable);
        timeoutHandle = setTimeout(function() { throttledObservable(val); }, throttleTime);
    });

    return throttledObservable;
}

Using it is simple:

// Usage:
var existingObservable = ...;
var throttleTime = ko.observable(500);
var throttled = existingObservable.throttle(throttleTime);

// Change the throttle willy nilly!
throttleTime(1000);

If you're doing lots of stuff like this (throttling, composing different observables together), you might be interested in Rx.js.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top