Javascript 为什么不';我有';这';我的余烬组件中.then()的内部上下文

Javascript 为什么不';我有';这';我的余烬组件中.then()的内部上下文,javascript,ember.js,this,Javascript,Ember.js,This,我对灰烬还不太熟悉 这是我的组件的代码: import Ember from 'ember'; export default Ember.Component.extend({ profiles: Ember.inject.service(), tagName: 'td', classNames: ['grey'], classNameBindings: ['unreadMessages'], unreadMessages: null, onInit: function()

我对灰烬还不太熟悉

这是我的组件的代码:

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.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在其
中返回的布尔值。然后()
,我无法调用
中的this.set()
。然后()
我正在寻找解决方法。我想我很接近,并且由于我缺乏与灰烬的经验,我很难做到这一点

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')
});

这里的问题是,当您在内部编写
function(){}
时,作用域会发生变化,
this
不会引用此组件。 这就是为什么在ES6中引入了词法
这个
的概念。这将保留
。因此,改用箭头功能,它将顺利工作。

更改

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

这里的问题是,当您在内部编写
function(){}
时,作用域会发生变化,
this
不会引用此组件。
这就是为什么在ES6中引入了词法
这个
的概念。这将保留
。因此,改用箭头函数,它将顺利工作。

这是一个正常的js调整,范围已更改,您没有使用箭头函数:)这不是“上下文”。它是执行上下文的一个参数,由调用、使用bind或从箭头函数中包含的执行上下文中采用。我建议您在
init
方法内部编写它,而不是('init')
,这是一个很好的实践。您还应该阅读它是一个普通的js调整,范围已更改,并且您没有使用箭头函数:)这不是“上下文”。它是执行上下文的一个参数,由调用、使用bind或从arrow函数中包含的执行上下文中采用。我建议您在
init
方法内部编写它,而不是('init')
,这是一个很好的实践。您还应该阅读好的答案。我使用的另一个技巧(Babel之前)是将
this
赋值给一个变量(我更喜欢将其命名为
self
),然后使用
self
而不是
this
。每当你在JS中看到“函数”时,一定要记住“这不是你所期望的…”。回答得好。我使用的另一个技巧(Babel之前)是将
this
赋值给一个变量(我更喜欢将其命名为
self
),然后使用
self
而不是
this
。每当你在JS中看到“函数”时,一定要记住“这不是你所期望的……”。