Search code examples
javascriptknockout.jssammy.js

Nested observables in knockoutjs


In a web app based on Knockoutjs and Sammy.js I have three observables that depend on each other in a parent-child way (the second is child of the first, the third is child of the second). My HTML has three sections where only one should be visible at a time. Each section depends on one of the mentioned observables using the visible binding.

My URL scheme is laid out like /#id-of-parent/id-of-child/id-of-grandchild (in Sammy.js).

If I access a full URL (one with all three ids) I get into trouble with the observables. In the Sammy rule function I first load and store the parent, then the child and lastly the grandchild (which is really the data the user wants to see). The problem is that the bindings for the parent and the child are also triggered.

Is there a way to avoid triggering the bindings or is there a better way to organise an app like this?

Here are my Sammy routes:

Sammy(function() {
  this.get('#study/:id', function() {
    self.studylist(null);
    self.currentStudy(Study.loadById(this.params.id));
  });

  this.get('#study/:id/variableGroups', function() {
    self.variableGroupList(self.currentStudy().variableGroups());
    self.currentVariable(null);
  });

  this.get('#study/:id/variable-group/:variableGroup/variables', function() {
    var groupId = this.params.variableGroup;
    $.ajax(apiUrl + "/variable-group/" + groupId, {
      type: "GET",
      async: false,
      cache: false,
      context: this,
      success: function(data) {
        if (!self.currentStudy()) {
          self.currentStudy(Study.loadById(this.params.id));
        }
        self.currentVariableGroup(new VariableGroup(data.variablegroup));
        self.variableList(self.currentVariableGroup().variables);
      }
    });
  });

  this.get('#study/:id/:variableGroupId/:variableId', function() {
    var variableId = this.params.variableId;
    $.ajax(apiUrl + "/variable/" + variableId, {
      type: "GET",
      async: false,
      cache: false,
      context: this,
      success: function(data) {
        if (!self.currentStudy()) {
          self.currentStudy(Study.loadById(this.params.id));
        }
        if (!self.currentVariableGroup()) {
          self.currentVariableGroup(VariableGroup.loadById(this.params.variableGroupId));
        }
        self.currentVariable(new Variable(data.variable));
      }
    });
  });

  this.get("", function() {
    self.currentStudy(null);
    self.currentVariableGroup(null);
    self.currentVariable(null);
    $.get(apiUrl + "/study/all", function(data) {
      var mappedStudies = $.map(data.studies, function(item, index) {
        return new Study(item);
      });
      self.studylist(mappedStudies);
    });
  });

  this.get('', function() { this.app.runRoute('get', "")});

}).run();

Solution

  • I don't think this is possible, and with good reason. It violates the principles of data-binding to update a subscribable without notifying subscribers. I strongly encourage you to refactor your program so that updating currentStudy and currentVariableGroup doesn't cause unwanted side effects. Let some other factor determine the desired effect, perhaps an activeTemplate observable.

    In any case, here is the source code for observable. Note that the inner value is a private member and cannot be accessed from outside. It can only be set by calling the observable (which notifies subscribers).

    ko.observable = function (initialValue) {
        var _latestValue = initialValue; //Value is in closure, inaccessible from outside
    
        function observable() {
            if (arguments.length > 0) {
                // Write
    
                // Ignore writes if the value hasn't changed
                if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
                    observable.valueWillMutate();
                    _latestValue = arguments[0];
                    if (DEBUG) observable._latestValue = _latestValue;
                    observable.valueHasMutated();
                }
                return this; // Permits chained assignments
            }
            else {
                // Read
                ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
                return _latestValue;
            }
        }