【问题标题】:Knockout observable array remove after index索引后删除可观察数组
【发布时间】:2014-04-03 09:07:51
【问题描述】:

我正在寻找一种方法来删除可观察数组中给定索引之后的所有元素。

执行此操作的 for 循环效率低下,因为一次删除一个元素会在每次删除时触发更改通知。有什么开箱即用的吗?

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    试试这个(注意 HowMany 是可选的,如果你不指定它,StartIndex 之后的所有项目都会被删除):

    myObservableArray.splice(StartIndex, HowMany)
    

    如果你需要删除具有某些属性的项目,你可以传递一个返回布尔值的函数给knockout的remove函数,例如:

    myObservableArray.remove(function(item) { return item.property > YourValue })
    

    + 引自淘汰文档:LINK

    Normally, an observableArray notifies its subscribers immediately, as soon as it’s 
    changed. But if an observableArray is changed repeatedly or triggers expensive updates,
    you may get better performance by limiting or delaying change notifications. This is
    accomplished using the rateLimit extender like this:
    
    // Ensure it notifies about changes no more than once per 50-millisecond period
    myViewModel.myObservableArray.extend({ rateLimit: 50 });
    

    【讨论】:

    • item.id 在我的情况下是未定义的,我不在我的模型中保留索引。关于更改通知的重要信息!需要记住这一点。
    • 所以也许只是使用 array.splice(indexOfStart,HowMany)?
    • 哦,显然 Knockout 提供了可观察数组的拼接!我会用那个。请随时更新您的答案,以便我接受。
    • 它已经更新了。显然你没有刷新页面;)
    猜你喜欢
    • 2017-07-19
    • 2012-12-07
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多