9

サーバーと通信して現在の画面形状などを報告する機能があります。

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

私はこの関数を次のようなコード内のいくつかのイベントにサブスクライブします。

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

これらのイベントの一部は、サーバーで適切に処理できないほど頻繁に送信される可能性があるため、要求をある程度の適切な速度に抑制したいと思います。

私が思いついた最高のものは次のようなものでした:

var triggerSend = ko.observable();

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

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

このパターンをキャプチャするためのより簡潔な方法はありますか、それともこれが進むべき方法ですか?

4

3 に答える 3

10

アンダースコアを使用している場合は、次のように使用できます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 });

1つの関数で多数のプロパティに添え字を付け、サーバーを更新する前にユーザーがクリックを停止する時間を与えることができます。

ありがとう、とても良いです!

于 2014-02-20T15:57:50.957 に答える