gpt4 book ai didi

javascript - 为什么我的 Ember 组件中的 .then() 内部没有 'this' 上下文

转载 作者:行者123 更新时间:2023-12-01 03:26:39 25 4
gpt4 key购买 nike

我对 Ember 还很陌生。

这是我的组件的代码:

import Ember from 'ember';

export default Ember.Component.extend({
profiles: Ember.inject.service(),
tagName: 'td',
classNames: ['grey'],
classNameBindings: ['unreadMessages'],
unreadMessages: null,

onInit: function() {
const id = this.get('conversation.id');
return this.get('profiles').getMessages(id)
.then(function(bool) {
this.set('unreadMessage', bool);
});
}.on('init')
});

这会抛出:

TypeError: Cannot read property 'set' of undefined

所以我可以推断我没有 this我需要调用的上下文this.set .then()里面

我需要分配return this.get('profiles').getMessages(id)的结果到unreadMessages我的组件中的属性。这样我就可以将它用于 classNameBinding

这是我从服务调用的方法

  getMessages(id){
return this.get('ajax').request('/messages?id=' + id)
.then((obj) => {
const unreadMessages = obj.messages.filter((e) => e.read === false);

if (unreadMessages === []) {
return false;
} else {
return true;
}
});
}

我只能访问 getMessages 在其 .then() 内部返回的 bool 值我无法调用 this.set() .then()里面我正在寻找解决方法。我认为我已经很接近了,但由于缺乏使用 Ember 的经验,我正在努力。

getMessages制作 'GET'向我的后端请求并过滤消息以检查是否有未读的消息,然后返回 true 或 false。 classNameBinding的目的是通知用户该线程是否有未读消息。这是一个非常简单的电子邮件风格的消息应用程序,我正在为练习而构建。

谢谢!

最佳答案

改变

onInit: function() {
const id = this.get('conversation.id');
return this.get('profiles').getMessages(id)
.then(function(bool) {
this.set('unreadMessage', bool);
});
}.on('init')
});

onInit: function() {
const id = this.get('conversation.id');
return this.get('profiles').getMessages(id)
.then((bool) => {
this.set('unreadMessage', bool);
});
}.on('init')
});

这里的问题是,当您在 then 中编写 function(){} 时,范围会发生变化,并且 this 不会引用组件 this。这就是为什么在 ES6 中引入了词法 this 的概念。这将保留 this。所以使用箭头函数来代替,它会顺利工作..

关于javascript - 为什么我的 Ember 组件中的 .then() 内部没有 'this' 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44779555/

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