gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:07:49 25 4
gpt4 key购买 nike

在 Ember.js 中使用 ember-data 时,我可以在 .hbs 模板中访问模型的属性,如下所示:

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

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

// 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

我广泛寻找解决这个问题的方法,但一无所获,所以我问这个问题:

使用 Ember.js 和 ember-data 时是否可以访问 Javascript 代码中模型实例的属性?如果是这样,该怎么办?如果不是,为什么我不能这样做?

作为引用,这是我当前的 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
}

关于javascript - Ember.js:如何在 Javascript 代码中访问模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39457714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com