在 Knockoutjs 中绑定到二叉树
我正在寻找一些关于将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
RP Niemeyer 向我指出了 valueHasMutated 的解决方案。第一轮只是在每次处理树时添加对 viewModel.bTree.valueHasMutated() 的调用。
一旦这被证明是有效的,代码就会被重构以将回调方法传递给树,这样每当树发生变化时,回调就会被调用。我们在闭包方面遇到了一些问题,但最终遇到了以下问题:
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: