9

I have a function that performs some communication with a server to report the current screen geometry, etc.

    function sendScreenLayout() { 
        logElementLocations(exp.getPageCoordinates());
    };

I subscribe this function to some events in my code like this:

viewModel.onLayoutChange.subscribe(sendScreenLayout);
$('#right-splitter > #mainContent').resize(sendScreenLayout);
$(window).resize(sendScreenLayout);
...
setTimeout(sendScreenLayout, 1);

Some of these events may get sent too frequently to be usefully handled by the server, and I would like to throttle the requests to some reasonable rate.

The best I could come up with was something like this:

var triggerSend = ko.observable();

ko.computed(function() {
    triggerSend();
    logElementLocations(exp.getPageCoordinates());
}).extend({throttle: 200});

function sendScreenLayout() {
    triggerSend.valueHasMutated();
}

Is there a more succinct way of capturing this pattern, or is this the way to go?

4

3 回答 3

10

如果您使用的是Underscore,则可以这样使用debounce

var sendScreenLayout = _.debounce(function() { 
    logElementLocations(exp.getPageCoordinates());
}, 200);
...
$(window).resize(sendScreenLayout);
...

否则,它并不是真正的 Knockout 直接支持的模式。您提出的解决方案似乎足够好,尽管这里有一个替代方案:

var triggerSend = ko.computed({
    read: function() {},
    write: function(dummy) {
        logElementLocations(exp.getPageCoordinates());
    }
}).extend({throttle: 200});

function sendScreenLayout() {
    triggerSend(true);
}
于 2012-08-27T20:23:50.307 回答
4

假设您viewModel.onLayoutChange是可观察的,您可以简单地执行以下操作:

ko.computed(function() {
    viewModel.onLayoutChange(); //implicitly subscribes this callback to changes
    logElementLocations(exp.getPageCoordinates());
}).extend({throttle: 200});
于 2013-05-31T20:53:17.890 回答
0

上面的答案很优雅!我有一个必须排序的列表,顺序以及到那时需要作为用户偏好保存到服务器的内容。我想在 3 个不同的属性更改上更新服务器,但不是每次更改。做这样的事情。

ko.computed(function () {
    self.sort.direction();
    self.sort.order();
    self.sort.groupByPIC();

    if (!_firstLoad) {
        _dataService.updateSortPreferences({
            model : new _jsSortModel(self.sort)
        });
    }
}).extend({ throttle: 2000 });

允许我使用一个函数为多个属性下标,并让用户有时间在更新服务器之前停止单击。

很好谢谢!

于 2014-02-20T15:57:50.957 回答