Suspend bindings in knockout.js 1.2.1

痴心易碎 提交于 2019-12-05 05:36:28

I don't think there is a way to suspend binding in knockout.js. Without seeing the code it's hard to say, but the slowness is probably caused by the fact that you refresh you observableArrays by clearing them and adding new items one by one. Instead you can refresh the entire array at once:

...
self.manyItems = ko.observableArray();
...
function refreshItems(newItems){
    self.manyItems(newItems);
}

Suspending and resuming is possible: take a look at this demo put together by Ryan Niemeyer. Refer to this entry on his blog for more background information.

If you really need to pause subscriptions still, I found a way to pause them in computed observables with a pauseableComputed (idea taken from this site). I modified it a bit to add the pauseableComputed the ability to have read and write functions.

viewModel.myComputedObservable = ko.pauseableComputed(function() {
    return myResult;
}, viewModel);

For pausing, you call myComputedObservable.pause();, make all your modifications and then call myComputedObservable.resume(); for those modifications to trigger the subscriptions in the computed observable.

   //wrapper for a computed observable that can pause its subscriptions
        ko.pauseableComputed = function (evaluatorFunction, evaluatorFunctionTarget) {
            var _cachedValue = "";
            var _isPaused = ko.observable(false);

            //the computed observable that we will return
            var result;
            if (evaluatorFunction.read) {
                result = ko.computed({
                    read: function() {
                        if (!_isPaused()) {
                            //call the actual function that was passed in
                            return evaluatorFunction.read.call(evaluatorFunctionTarget);
                        }
                        return _cachedValue;
                    },
                    write: function(value) {
                        if (!_isPaused()) {
                            //call the actual function that was passed in
                            return evaluatorFunction.write.call(evaluatorFunctionTarget, value);
                        }
                        return _cachedValue;
                    }
                }, evaluatorFunctionTarget);
            } else {
                result = ko.computed(function() {
                    if (!_isPaused()) {
                        //call the actual function that was passed in
                        return evaluatorFunction.call(evaluatorFunctionTarget);
                    }
                    return _cachedValue;
                }, evaluatorFunctionTarget);
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!