开发者

Binding to a Binary Tree in Knockoutjs

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.dependent开发者_StackOverflow中文版Observable(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'));


RP Niemeyer pointed me to the solution with valueHasMutated. The first round was just adding a call to viewModel.bTree.valueHasMutated() every time we worked with the tree.

Once this was proven to work, the code was refactored to pass a callback method to the tree, so that any time the tree changed, the callback would be invoked. We ran into some problems with closures, but finally got to the following:

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); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜