0

Here is a fork of code that nemesv wrote:

http://jsfiddle.net/GbCYp/4/

There is a parent node and nested children.

Here is a sample of the parent/child node:

 function FormElementNode(children, text, value) {
   var self = this;
   self.children = ko.observableArray(children);
   self.text = ko.observable(text);
   self.value = ko.observable(value);
} 

And here is the structure of the HTML (without the script tags)

<ul>
   <li>Parent text value:
      Children: 
      <ul>
         <li>Child1 text value</li>
         <li>Child2 text value</li>
   </li>

I need to be able to select a node by mouse-clicking it (in effect, select one of the li-tags via a mouse click); then press the delete button to remove it (last line of the code). How can I do that?

4

1 回答 1

1

我认为您可能必须更改视图模型:创建一个新模型,其中包含 observableArray 中的根父项列表。然后,您将能够绑定对每个元素的单击(单击要删除的元素),并将功能绑定到单击“删除我”。

这是一个例子:

var Element = function(children, text, value) {
    var self = this;
    self.text = ko.observable(text);
    self.value = ko.observable(value);
    self.children = ko.observableArray([]);

    if(children) {
        for(var i = 0; i < children.length; i++) {
            var child = children[i];
            self.children.push(new Element(child.children, child.text, child.value));
        }
    }
}

var Model = function(data) {
    var self = this;
    this.els = ko.observableArray([]);
    this.currentClicked = null;
    for(var i = 0; i < data.length; i++) {
        var element = data[i]
        var el = new Element(element.children, element.text, element.value);
        self.els.push(el);
    }
    this.click = function(el) {
        self.currentClicked = el;

    }
    this.remove = function() {
        self.els.remove(self.currentClicked);
        for(var i = 0; i < self.els().length; i++) {
            self.findAndRemove(self.els()[i], self.currentClicked);
        }
    }

    this.findAndRemove = function(element, toFind) {
        element.children.remove(toFind);
        for(var i = 0; i < element.children().length; i++) {
            self.findAndRemove(element.children()[i], toFind);
        }
    }

}

这个例子显然没有优化,但这可以让你了解我的意思。这是一个对应的jsfiddle: http: //jsfiddle.net/JHK8b/1/您可以点击任何元素名称,然后点击“删除我”。

于 2013-07-16T12:22:25.193 回答