在 Knockoutjs 中绑定到二叉树

发布于 2024-12-02 01:39:04 字数 592 浏览 1 评论 0原文

我正在寻找一些关于将 knockoutjs 绑定到具有 dependentObservables 的二叉树的建议。

我正在开发一个涉及 javascript 中的二叉树的 Web 项目。二叉树实现已经完成,我在使用 Knockoutjs 时遇到了问题。

二叉树实际上没有任何属性,只有几个方法(addNode、inorderTraversal、getLength、getDepth、toJSON 等),所以我不知道如何将其设置为可观察的。我真的很想有一些依赖的 Observables 从二叉树中获取一些信息。

作为一个简单的例子,我想至少为树的长度设置一个 dependentObservable 。它似乎永远不会被触发...

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

以下将节点添加到树中,但 TreeLength 永远不会触发。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女净妖师 2024-12-09 01:39:04

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

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); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文