Here is a fork of code that nemesv wrote:
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?
I think that you'll probably have to change your view Model: make a new model that contains a list of root parents in an observableArray. Then, you will be able to bind a click on each element (to click on the element to delete), and to bind a function to the click on "delete me".
Here is an example:
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);
}
}
}
This example is clearly not optimized, but that could give you an idea about what I mean. Here is a corresponding jsfiddle: http://jsfiddle.net/JHK8b/1/ You can click on any element name and then click on "delete me".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.