敲除foreach循环迭代相同的数据元素

时间:2012-04-17 15:21:23

标签: javascript asp.net-mvc-3 knockout.js

我有一个包含4个元素的数组,并通过绑定到foreach循环传递。

   <ul data-bind="foreach: relatives">
        <li>
            <span data-bind="text: First"></span>
            <span data-bind="text: Last"></span>
            <span>
                <a href="#" class="tag-edit">Edit</a> 
                <a href="#" class="tag-delete">Delete</a>
            </span>
        </li>
    </ul>

出于某种原因,我的输出在我的调试中给了我一个相对四次我在我的数据数组中只有四个亲戚我做了可观察的。我的html显示了redudant条目。它非常清楚我没有犯错我的数组它显然有4个元素但是foreach循环表现得很奇怪。

使用Knockout的Javascript:

var data = [
    { Id: 1, First: "John", Last: "Doe", Address: "76 Hero Ave" },
    { Id: 2, First: "Bill", Last: "Doe", Address: "467 Nantucket Rd" },
    { Id: 3, First: "Sue", Last: "Doe", Address: "467 Nantucket Rd" },
    { Id: 4, First: "Jane", Last: "Doe", Address: "76 Hero Ave" },
];

var viewModel = {
    // data
    relatives: ko.observableArray(data),
    firstNameToAdd: ko.observable(""),
    lastNameToAdd: ko.observable(""),

    // behaviors
    addRelative: function () {
        this.relatives.push({ First: this.firstNameToAdd(), Last: this.lastNameToAdd()        });
        this.firstNameToAdd("");
        this.lastNameToAdd("");
    }
};

$(document).on("click", ".tag-delete", function () {
    var itemToRemove = ko.dataFor(this);
    viewModel.relatives.remove(itemToRemove);
});

ko.applyBindings(viewModel);

添加了viewModel代码块中添加的click click,我的列表将不再显示任何内容。我的调试显示我的数据中没有任何内容,也没有显示出来。

1 个答案:

答案 0 :(得分:1)

试试这个:

查看

<ul data-bind="foreach: relatives">
    <li>
        <span data-bind="text: First"></span>
        <span data-bind="text: Last"></span>
        <span>
            <a href="#" class="tag-edit">Edit</a> 
            <a href="#" data-bind="click: $parent.remove">Delete</a>
        </span>
    </li>
</ul>

的Javascript

var data = [
    { Id: 1, First: "John", Last: "Doe", Address: "76 Hero Ave" },
    { Id: 2, First: "Bill", Last: "Doe", Address: "467 Nantucket Rd" },
    { Id: 3, First: "Sue", Last: "Doe", Address: "467 Nantucket Rd" },
    { Id: 4, First: "Jane", Last: "Doe", Address: "76 Hero Ave" },
];

​var viewModel = {
    // data
    relatives: ko.observableArray(data),
    firstNameToAdd: ko.observable(""),
    lastNameToAdd: ko.observable(""),


    // behaviors
    addRelative: function() {
        this.relatives.push({
            First: this.firstNameToAdd(),
            Last: this.lastNameToAdd()
        });
        this.firstNameToAdd("");
        this.lastNameToAdd("");

    },

    remove: function(item) {
        viewModel.relatives.remove(item);
    },
};

ko.applyBindings(viewModel);​