繁体   English   中英

如何在一起调用多个订阅变量时仅调用一次函数

[英]How to call function only once when multiple subscribed variables are called together

这不是一个特别的技术问题,但我很好奇这个问题的最佳方法是什么? 虽然我在Knockout中有这个问题,但我确信用例在其他地方也是有效的。

假设我已经订阅了2个变量simpleObserve1simpleObserve2这样每次它们的值发生变化时,它们都会调用一个函数resetAllValues()

var simpleObserve1 = ko.observable(0), // initial values
    simpleObserve2 = ko.observable(0); // initial values

var resetAllValues = function resetAllValues() {
    /* this function takes all observable values and resets them */
    {...}
}

simpleObserve1.subscribe(function(){
    resetAllValues();
});

simpleObserve2.subscribe(function(){
    resetAllValues();
});

simpleObserve1(5); // value changed anywhere in code
simpleObserve2(10); // value changed anywhere in code

这里有2个问题。

  1. 调用resetAllValues()时,它会将所有订阅的值更改为0,包括simpleObserve1simpleObserve2 这又反过来调用resetAllValues() 如何防止这种情况进入无限循环?
  2. 如果我想一起更新两个变量,但只调用一次resetAllValues()怎么办?

我试图使用knockout的dispose()方法帮助我,但我想知道是否有更好的方法来做到这一点。

延期更新可能会帮助您。 通过在计算中使用observables的值,knockout创建订阅。 通过扩展这个计算,快速成功的变化被组合在某种微任务中。

它们可以防止循环行为,但仍然不清楚触发了多少更新。 即:当设置为510产生12个计算更新。 所以我不完全确定这是否能回答你的问题。

 var i = 0, simpleObserve1 = ko.observable(0), // initial values simpleObserve2 = ko.observable(0); // initial values ko.computed(function resetAllValues() { console.log("Set " + ++i + ", before:"); console.log("1: ", simpleObserve1()); console.log("2: ", simpleObserve2()); simpleObserve1(0); simpleObserve2(0); console.log("Set " + i + ", after:"); console.log("1: ", simpleObserve1()); console.log("2: ", simpleObserve2()); }).extend({ deferred: true }); simpleObserve1(5); // value changed anywhere in code simpleObserve2(10); // value changed anywhere in code 
 .as-console-wrapper { min-height: 100%; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 

我创建了一个更高阶函数acceptXParams ,它将检查params的数量是否等于fn.length或任意数字。 如果不是,则不会调用原始函数:

 function acceptXParams(fn, numOfParams) { var numOfParams = numOfParams === undefined ? fn.length : numOfParams; return function() { if(arguments.length !== numOfParams) { return; } return fn.apply(fn, arguments); } } /** example **/ function sum(a, b, c) { return a + b + c; } var sum3 = acceptXParams(sum); console.log(sum3(1, 2, 3)); console.log(sum3(1, 2)); console.log(sum3(1, 2, 3, 4)); 

更时尚的ES6版本acceptXParams

const acceptXParams = (fn, numOfParams = fn.length) => 
    (...args) => 
        args.length === numOfParams ? fn(...args) : undefined;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM