How to call a function only once when several signed variables are called together

This is not a technical question, but I was curious which approach is best suited for such a problem? Although I have this problem in Knockout, I’m sure that the use case will be valid elsewhere.

Suppose that I have signed a two variables simpleObserve1, simpleObserve2so that every time changes their meaning, they call the function 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 questions here.

  • When resetAllValues ​​() is called, it changes all signed values ​​to 0, including simpleObserve1and simpleObserve2. This, in turn, calls resetAllValues()again and again. How can I prevent this from going into an infinite loop?
  • , , resetAllValues() ?

knockout dispose(), , , .

+4
2

. , . , , - -.

, , . I.e.: 5 10 1 2 . , .

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>
Hide result
+1

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));
Hide result

ES6 acceptXParams:

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

Source: https://habr.com/ru/post/1658761/


All Articles