3

I'm looking for some advice on binding knockoutjs to a binary tree with dependentObservables.

I'm working on a web project that involves a binary tree in javascript. The binary tree implementation has been completed, and I'm running into a problem using it with Knockoutjs.

The binary tree doesn't really have any properties, only a few methods (addNode, inorderTraversal, getLength, getDepth, toJSON, etc), so I have no clue how to set it up as observable. I'd really just love to have a few dependentObservables that get some information from the binary tree.

As a simple example, I'd like to at least set up a dependentObservable for the length of the tree. It just never seems to get fired...

viewModel.TreeLength = ko.dependentObservable(function(){
return this.bTree().getLength();}, viewModel);

The following adds the node to the tree, but the TreeLength never fires.

viewModel.bTree().addNode(new Node('some data'));
4

1 回答 1

4

RP Niemeyer 向我指出了 valueHasMutated 的解决方案。第一轮只是在我们每次使用树时添加对 viewModel.bTree.valueHasMutated() 的调用。

一旦证明这是可行的,代码就会被重构以将回调方法传递给树,以便每当树发生变化时,都会调用回调。我们遇到了一些闭包问题,但最终得到了以下问题:

function getCallBack(o) 
{
  var obj = o;
  var func = function() 
  {
    obj.bTree.valueHasMutated();
  }

  return func;
}

this.bTreeChanged = getCallBack(this);
model.bTree = new BinaryTree(model.treeData, this.bTreeChanged); 
于 2011-09-12T19:50:01.890 回答