Ember.js:如何在Javascript代码中访问模型的属性

Ember.js: How to access a model's attributes inside Javascript code

本文关键字:访问 模型 属性 代码 Javascript js Ember      更新时间:2023-09-26

在Ember.js中使用ember-data时,我可以在.hbs模板中像这样访问模型的属性:

{{#each model as |person|}}
    Welcome, {{person.firstName}} {{person.lastName}}!
{{/each}}

我尝试使用以下方法在Javascript代码中访问这些值(无论是在控制器还是组件中):

// Method 1
if (person.firstName === 'Jack') {
    // Do something when the first name is Jack
}
// Method 2
if (person.get('firstName') === 'Jack') {
    // Do something when the first name is Jack
}

但是这些都不能得到当前模型的任何属性。我能得到的唯一值是当前模型实例的id

我已经四处寻找这个问题的解决方案,但一无所获,所以我问这个问题:

是否可以访问Javascript代码中的模型实例的属性,而使用Ember.js和ember-data?如果可以,如何做到这一点?如果没有,为什么我不能这么做?

作为参考,这是我目前的Ember.js设置:

DEBUG: Ember             : 2.5.1
DEBUG: Ember Data        : 2.5.3
DEBUG: jQuery            : 2.2.4
DEBUG: Ember Simple Auth : 1.1.0

当你有一个要传递给组件的对象时,它就变成了组件的属性。因此,在访问模型对象本身的任何属性之前,你需要通过组件的属性获得该对象。

假设你像这样将对象传递给组件:

{{person-profile person=person}}

这两个都可以:

// Method 3
if (this.get('person').get('firstName') === 'Jack') {
  // Do something when the first name is Jack
}
// Method 4
if (this.get('person.firstName') === 'Jack') {
  // Do something when the first name is Jack
}