1

第一周在这里使用 KnockoutJS 并寻找一种简单的方法来从其动态添加的父数组中删除子数组。访问http://jsfiddle.net/hotdiggity/HC9wU/以获取以下工作示例:

function Parent(name, children) {

    var self = this;

    //self.name = ko.observable(name);

    self.children = ko.observableArray(children);

    self.addChild = function () {
        self.children.push(new Child(""));
    }

    self.removeParent = function (parent) {
        vm.removeParent(self);
    };

}

function Child(name) {

    var self = this;

    //self.name = ko.observable(name);

    self.removeChild = function (child) {
        vm.removeChild(self);
        // this.child.remove(child);
    };
}

function ParentChildViewModel() {

    var self = this;

    self.parents = ko.observableArray([]);

    self.addParent = function () {
        self.parents.push(new Parent("", []));
    };

    self.removeParent = function (parent) {
        self.parents.remove(parent);
    }

    // remove child from the children list somehow
    self.removeChild = function (child) {
        self.children.remove(child);
    }

};

var vm = new ParentChildViewModel();
ko.applyBindings(vm);
4

2 回答 2

1

Parent您可以在 中存储对 的引用Child,并将该removeChild函数移动到父级而不是 VM 中。然后从内部Child你可以做这样的事情:

self.removeChild = function () {
    self.parent.removeChild(self);
};

这是一个jsfiddle

于 2013-11-09T02:23:16.890 回答
0

http://jsfiddle.net/cKzn8/5/

问题是ParentViewModel它没有孩子。

// remove child from the children list somehow
self.removeChild = function (child) {
    self.children.remove(child);
}

我添加了对父级的引用:

self.removeChild = function (child) {
    child.parent.children.remove(child);
    // this.child.remove(child);
};
于 2013-11-09T02:23:57.463 回答