敲除可观察数组并没有更新从数组中移除元素的视图

knockout observable array is not updating view on removing elements from array

本文关键字:数组 元素 视图 更新 观察 并没有      更新时间:2024-01-04

这是我的视图模型代码

var TopicsViewModel = function() {
var self = this;
var fakeTopicData =
 [
 ];

self.createProfile = function () {
    alert("came to create profile");
};
self.editProfile = function () {
    alert("came to edit profile");
};
self.removeProfile = function (profile) {
    alert("came to remove profile");
    fakeTopicData.pop();
    self.topicsArr(fakeTopicData);
};

var refresh = function() {
    self.topicsArr = fakeTopicData;
};

self.topicsArr = ko.observableArray([]);
refresh();
  };

  ko.applyBindings(new TopicsViewModel());

这是我的html视图:

<hr /> 
<hr /> 
<table  class="table table-striped table-bordered table-condensed">
    <tr >
        <th>Area</th>
        <th>Name</th>
        <th>Link</th>
        <th>Description</th>
        <th>Why</th>
    </tr>
    <tbody data-bind="foreach : topicsArr">   
        <tr>
            <td data-bind="text :area"> </td>
            <td class=""><a data-bind="text:name, click:$parent.editProfile"></a></td>           
            <td data-bind="text:link"> </td>
            <td data-bind="text:desc">  </td>
            <td data-bind="text:why" ></td>
            <td><button class="btn btn-mini btn-danger" data-bind="click:$parent.removeProfile">remove</button></td>
        </tr>
    </tbody>
</table>
 <script src="~/Scripts/Topic.js"></script>

该视图最初显示fakeData数组中的所有Topics。单击删除按钮时,我正试图从数组中删除一个元素,并希望视图刷新,不再显示已删除的项。然而,视图仍然显示了所有3个主题。

有人能指出我可能做错了什么吗。我花了很长时间研究stackoverflow上的其他类似查询,但仍然被卡住了。非常感谢您对这个问题的深入了解。

您正在将名为topicsarr的可观察数组替换为在刷新方法中不可观察的数组。。。

更改

var refresh = function() {
    self.topicsArr = fakeTopicData;
};

var refresh = function() {
    self.topicsArr(fakeTopicData);
};

您的代码中有两个问题
首先,在refresh函数中使用nonobservableArray或普通数组设置observableArray topicsArr。而是使用self.topicsArr(fakeTopicData)

第二个,在函数removeProfile中,您正在使用pop()删除profile元素。来自KnockoutJS文档:

myObservableArray.pop()从数组中删除最后一个值返回

因此,最好使用remove(item)并将您的profile元素传递给它,或者在数组中循环并移除特定项目

myObservableArray.remove(someItem)删除所有等于someItem并将其作为数组返回