【问题标题】:Ember observe nested array propertyEmber 观察嵌套数组属性
【发布时间】:2023-03-21 02:02:01
【问题描述】:

我想观察一个嵌套属性。我有以下 Ember 数组:

specifications: [
  {
    title: "specification name",
    filters: [
      {
        title: "example"
        checked: false
      },
      {
        title: "example 2",
        checked: true
      }
    ]
  },
  ...
]   

我想创建一个计算属性:

activeFilters: (->
  Ember.computed.filterBy('specifications.@each.filters', 'checked', true),
).property('specifications.@each.filters')

active filters 属性不起作用,我尝试了几种属性方法的组合,但没有一个起作用。

我正在尝试创建的属性真的可行吗?

【问题讨论】:

  • 你的意思是specifications.filters.@each
  • 我注意到您从不接受答案。考虑结束您的一些问题。
  • 我现在就去做。

标签: ember.js


【解决方案1】:

是的,这是可能的。问题是,要让它工作,你不能使用 JavaScript 数组,你需要一个 Ember.ArrayProxy,然后你可以访问它的特殊属性:http://emberjs.com/api/classes/Ember.ArrayProxy.html

specifications: Ember.ArrayProxy.create({
  content: [
    {
      title: "specification name",
    },
  ]
});

所以,你会得到类似的东西:

oneSpecChangedCheck: function() {
  // don't know which, but someone changed
  var s = this.get('specs');
  // loop and process
  return s;
}.property('specs.@each.checked'),

http://emberjs.jsbin.com/zohuzo/2/edit?html,js,console,output

【讨论】:

  • 关于 ArrayProxy 的要点是,尽管我的 javascript 数组是出于示例目的。我正在使用的数组来自 Ember 数据。我创建了一个 jsbin 来模仿我的问题:emberjs.jsbin.com/mijise/5/edit?html,js,output How can I create the computed property checkedFilters based on all filters with checked == true. filterS 在 specificationS 中的嵌套让我很难理解。
  • 我找不到一种方法让它与filterBy 一起工作,这将“直接”返回元素。我引用“直接”是因为如果你查看函数的源代码,你会发现它也使用了@each
  • 我正在纠正,用filterBy 是不可能的。最接近的是使用自定义filter,但在我看来,它比计算属性更复杂,因为它们从外层到内层,而你想要相反。我发布的同一个小提琴有代码可以引导你得出同样的结论。
猜你喜欢
  • 2017-06-15
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多