Why is there a while loop in the baseline set method?

Github source code

The following is a snippet of the baseline installation method:

set: function(key, val, options) {
  var attr, attrs, unset, changes, silent, changing, prev, current;

  ...

  options || (options = {});

  ...

  // Trigger all relevant attribute changes.
  if (!silent) {
    if (changes.length) this._pending = options;
    for (var i = 0, length = changes.length; i < length; i++) {
      this.trigger('change:' + changes[i], this, current[changes[i]], options);
    }
  }

  // You might be wondering why there a `while` loop here. Changes can
  // be recursively nested within `"change"` events.
  if (changing) return this;
  if (!silent) {
    while (this._pending) {
      options = this._pending;
      this._pending = false;
      this.trigger('change', this, options);
    }
  }
  this._pending = false;
  this._changing = false;
  return this;
}

Although the comment mentioned a loop whilethat I’m interested in, I don’t see how this loop works, since the local variable changingwill always be truein one round set.

Can someone explain to me why there is time, and when will it take effect?

Thanks in advance!

+4
source share
1 answer

As the comment says: "Changes can be recursively nested in events "change"."

, "change" , set. _pending , , , "change", .

, , , , , 1 . , , , set. . unit test . , while 1 , set , , set . , :

model.on('change:a', function() {
  model.set({b: true});
  model.set({b: true});
});

, this._pending ,

+1

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


All Articles