Development Tip

계산 된 속성 함수를 강제 실행

yourdevel 2020. 10. 14. 21:19
반응형

계산 된 속성 함수를 강제 실행


계산 된 속성이 주어지면

vm.checkedValueCount = ko.computed(function(){
  var observables = getCurrentValues();  //an array of ko.observable[]
  return _.filter(observables, function(v) { return v() }).length;
});

getCurrentValues ​​()가 코드의 다른 곳에서 수정 된 (그리고 observableArray보다 더 복잡한 구조에서 온) 다른 관찰 가능 집합을 반환 할 수 있다고 가정합니다.

checkedValueCount언제든지 업데이트 해야 합니다.

  • 종속성 중 하나가 변경됩니다.
  • getCurrentValues ​​()는 다른 관찰 가능 항목 집합을 반환합니다.

문제는 ko.computed마지막으로 반환 된 값을 기억하고 종속성이 업데이트 될 때만 업데이트 되는 것 같습니다. 이것은 첫 번째 경우를 처리하지만 후자는 처리하지 않습니다.

내가 찾고있는 것은 checkedValueCount를 강제로 다시 실행하는 방법입니다. 다음과 같이 사용할 수있는 것 :

changeCurrentValues();
vm.checkeValueCount.recalculate();

가장 간단하게 말하면

a = ko.computed(function() { return Math.random() })

어떻게 강제로 a()두 번 호출 하여 다른 값을 반환 할 수 있습니까 ?


내 첫 번째 답변이 귀하의 요점을 놓치고 귀하의 문제를 해결하지 못할 것임을 깨달았습니다.

문제는 계산이 재평가를 강요하는 관찰 가능 항목이있는 경우에만 재평가된다는 것입니다. 계산 된 항목을 재평가하도록 강제하는 기본 방법은 없습니다.

그러나 더미 관찰 가능한 값을 만든 다음 구독자에게 변경되었음을 알리면 일부 해커로이 문제를 해결할 수 있습니다.

(function() {

    var vm = function() {
        var $this = this;

        $this.dummy = ko.observable();

        $this.curDate = ko.computed(function() {
            $this.dummy();
            return new Date();
        });

        $this.recalcCurDate = function() {
            $this.dummy.notifySubscribers();
        };        
    };

    ko.applyBindings(new vm());

}());​

다음은 이 접근 방식을 보여주는 Fiddle입니다.


사용자에 따라 모든 관찰 가능 항목을 강제로 다시 계산 하는 방법 이 있습니다.

getCurrentValues.valueHasMutated()

이 답변은 @josh가 준 것과 개념적으로 동일하지만 더 일반적인 래퍼로 제공됩니다. 참고 :이 버전은 '쓰기 가능'계산 용입니다.

Typescript를 사용하고 있으므로 먼저 ts.d 정의를 포함했습니다. 따라서 당신과 관련이 없다면이 첫 번째 부분을 무시하십시오.

interface KnockoutStatic
{
    notifyingWritableComputed<T>(options: KnockoutComputedDefine<T>, context ?: any): KnockoutComputed<T>;
}


알림 쓰기 가능 계산

쓰기 가능한 래퍼 observable것을 항상 더 관찰 가능한이의 결과로 업데이트되지 않은 경우에도 - 가입자의 원인을 통보하는 write전화

그냥 교체 function<T> (options: KnockoutComputedDefine<T>, context)와 함께 function(options, context)당신이 타이프 라이터를 사용하지 않는 경우.

ko.notifyingWritableComputed = function<T> (options: KnockoutComputedDefine<T>, context)
{
    var _notifyTrigger = ko.observable(0);
    var originalRead = options.read;
    var originalWrite = options.write;

    // intercept 'read' function provided in options
    options.read = () =>
    {
        // read the dummy observable, which if updated will 
        // force subscribers to receive the new value
        _notifyTrigger();   
        return originalRead();
    };

    // intercept 'write' function
    options.write = (v) =>
    {
        // run logic provided by user
        originalWrite(v);

        // force reevaluation of the notifyingWritableComputed
        // after we have called the original write logic
        _notifyTrigger(_notifyTrigger() + 1);
    };

    // just create computed as normal with all the standard parameters
    return ko.computed(options, context);
}

이것의 주요 사용 사례는 read함수에 의해 '방문'되는 관찰 가능 항목의 변경을 트리거하지 않는 무언가를 업데이트 할 때 입니다.

예를 들어 LocalStorage를 사용하여 일부 값을 설정하고 있지만 재평가를 트리거하기 위해 관찰 가능한 항목에는 변경 사항이 없습니다.

hasUserClickedFooButton = ko.notifyingWritableComputed(
{
    read: () => 
    {
        return LocalStorageHelper.getBoolValue('hasUserClickedFooButton');
    },
    write: (v) => 
    {
        LocalStorageHelper.setBoolValue('hasUserClickedFooButton', v);        
    }
});

모든 내가 변화를 필요로합니다이었다 ko.computedko.notifyingWritableComputed다음 모든 자체 처리합니다.

When I call hasUserClickedFooButton(true) then the 'dummy' observable is incremented forcing any subscribers (and their subscribers) to get the new value when the value in LocalStorage is updated.

(Note: you may think the notify: 'always' extender is an option here - but that's something different).


There is an additional solution for a computed observable that is only readble:

ko.forcibleComputed = function(readFunc, context, options) {
    var trigger = ko.observable().extend({notify:'always'}),
        target = ko.computed(function() {
            trigger();
            return readFunc.call(context);
        }, null, options);
    target.evaluateImmediate = function() {
        trigger.valueHasMutated();
    };
    return target;
};


myValue.evaluateImmediate();

From @mbest comment https://github.com/knockout/knockout/issues/1019.


suppose getCurrentValues() can return different sets of observables which are modified elsewhere in the code

I assume getCurrentValues() is a function. If you could make it a computed, your checkedValueCount would just magically start working.

Can you make getCurrentValues be a computed instead of a function?


since there is no straight forward way to force update a computed, i have created an observable named toForceComputedUpdate, and i called it within the computed function so the computed will listen to its update, then to force update i call it like this toForceComputedUpdate(Math.random)

참고URL : https://stackoverflow.com/questions/13769481/force-a-computed-property-function-to-run

반응형