javascript Ember - 如何从控制器的数组属性中添加/删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31852589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:27:33  来源:igfitidea点击:

Ember - How to add/remove elements from an array property on controller

javascriptarraysember.js

提问by Marco Prins

Given a controller in ember:

给定一个 ember 控制器:

export default Ember.Controller.extend({
  stringProp: "",
  arrayProp: []
});

You can, for example, set the string property with this.set('stringProp', "Blah blah"). But that is overriding. What I want to do is pushto the array property.

例如,您可以使用this.set('stringProp', "Blah blah"). 但这是压倒一切的。我想要做的是送到数组属性。

Is there a better (either shorter or faster) way than this:

有没有比这更好(更短或更快)的方法:

this.set('arrayProp', this.get('arrayProp').push(element));

Also, is there a shortcut for removingelements from such an array property?

另外,是否有从这样的数组属性中删除元素的快捷方式?

回答by

You are looking for pushObject, removeObject, etc. See http://emberjs.com/api/classes/Ember.MutableArray.html.

您正在寻找pushObjectremoveObject等见http://emberjs.com/api/classes/Ember.MutableArray.html

this.get('arrayProp').pushObject(element);

For correct behavior by computed properties and observers, it is strongly recommended you use these methods instead of pushor other native Array methods.

为了计算属性和观察者的正确行为,强烈建议您使用这些方法而不是push其他原生 Array 方法。