2016-11-09 151 views
1

我有一个数组中的项目列表。Aurelia删除项目后不显示正确的阵列表示

当我点击我认为这个项目,我试图删除这个项目

查看

<div class="lootItem" repeat.for="lootItem of stack"> 
    <div class="noselect" click.delegate="$parent.takeItem(lootItem)"> 
     <i class="fa fa-diamond"></i> ${lootItem.value} 
    </div> 
</div> 

视图模型

takeItem(lootItem){ 
    this.eventAggregator.publish(new ItemTaken(lootItem)); 
    console.log(_.includes(this.stack, lootItem)); //true 

    _.pull(this.stack, lootItem); //removes item and fails to update the ui 
    _.remove(this.stack, lootItem); //removes item and fails to update the ui 
    this.stack.shift(); //removes first item and updates the ui 
} 

两个.pull().remove()(使用lodash)将删除数组中的项但不更新ui。

.shift()设法从数组中删除项目,并更新所述用户界面。

为什么Aurelia在使用lodash时不会更新UI?

附录:可能值得注意的是,如果我点击相同的物品两次,那么_.includes第一次为真,然后第二次为假。

+2

?使用本机功能,您的代码将起作用。 –

+0

我熟悉很多lodash方法,这就是为什么我决定将它引入,这是否意味着操纵标准ES方法之外的数组将不起作用?现在看来我可以使用过滤器和操作数组,像这样:'this.stack = this.stack.filter(item => item!= lootItem);'。但是我觉得它不像一个简单的'.remove()'那么清晰。 – 4imble

+0

我不熟悉lodash的内部,但我发布了一个答案,显示了使用内置数组方法是多么简单。干杯! –

回答

3

Aurelia路上可以为您提供当前项目的索引。然后,只需使用内置的阵列中的方法ES2015提供:

查看

<div class="lootItem" repeat.for="lootItem of stack"> 
    <div class="noselect" click.delegate="$parent.takeItem($index, lootItem)"> 
     <i class="fa fa-diamond"></i> ${lootItem.value} 
    </div> 
</div> 

视图模型

takeItem($index, lootItem){ 
    this.eventAggregator.publish(new ItemTaken(lootItem)); 

    this.stack.splice($index, 1); 
} 
0

使用ES2015设置另一种方法是使用ES2015设置数据 结构。它可以与值数组进行初始化,并设置 原型甚至提供了删除方法用于去除特定值

...

然而,组语义是从规则阵列不同。通过定义 ,一组是唯一值的集合。因此,它不会包含重复项。如果您需要允许重复值为 的集合,则集合是错误的数据结构。

https://blog.mariusschulz.com/2016/07/16/removing-elements-from-javascript-arrays

我现在用一组这一点,它允许我使用.add().delete()。我只需要记住,一切都必须是独特的(在我的情况下,在这里)

我仍然想明白为什么操纵数组虽然lodash不起作用,但我会调查一下其他时间。


附录

您还可以使用原型:当一个中继器内使用$index变量

interface Array<T> { 
    remove(itemToRemove: T): Array<T>; 
} 

(<any>Array.prototype).remove = function (itemToRemove) { 
    const index = this.indexOf(itemToRemove); 
    if (index !== -1) { 
     this.splice(index, 1); 
    } 
    return this; 
} 
0

我相信你的问题就出在变量的作用域。

_.pull和_.remove正在返回一个数组的新实例。

你为什么要使用lodash时ES2015具有此功能内置尝试

this.stack = _.remove(this.stack, lootItem);

+1

根据文档它应该改变数组,检查变量显示它实际上已经删除了该项目,但它没有反映在视图中。 – 4imble