Knockout computed trigger several times in one action

I have a knockout problem with software that I am working on but have not created. This page performs autosave when almost any field is edited. The page displays several test questions, each of which is associated with answers (answers). Autosave is implemented using a dirty flag, which compares the current state of the object with the initial state.

The symptoms that I see are that when I first visit the page and add a new question, 1 api call arises for 1 new question (which is true). If I go to another page and return to the same test (or another), all api calls will be duplicated. If I repeat the same thing again, 3 calls are created (exactly the same). My theory is that something in VM / Obsable does not become properly unmanageable when you exit the page. I debugged this a lot, and I don’t think that there are several different actions that trigger the save, but 1 action that triggers the launch of the calculated functions, which launches autosave for every opening of any test. A browser update calls this invisible reset counter.

There are two computable functions.

self.dirtyQuestions = ko.computed(function() {
  return ko.utils.arrayFilter(self.current.assessmentItems(), function(question) {
    return question.dirtyFlag.isDirty();
  });
}, self).extend({ throttle: 250 });

self.triggerDirtyQuestionSave = ko.computed(function() {
  if (!CONFIG.editing.autoSave) {
    return;
  }
  if (self.dirtyQuestions().length > 0) {
    self.saveQuestions(self.dirtyQuestions(), true);
  }
}, self);

which, apparently, depend solely on the observed array

  assessmentItems: ko.observableArray([]),

. - , . , , , , .

: , - /VM/observablearray , , ? , , .

-

        create: {
      enter: [
        checkForUnsavedChanges,
        function () {
          self.closeOverlay();
      }],
      to: function() {
        assessmentAuthoringVM = new AssessmentAuthoringVM(self);
      },
      exit: function() {
        if (assessmentAuthoringVM) {
          assessmentAuthoringVM.destroy();
        }
      }
    },
+4
1

, , "" , "" :

destroy: function () {
    self.triggerDirtyQuestionSave.dispose();
    self.dirtyQuestions.dispose();
}
+1

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


All Articles