繁体   English   中英

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

[英]Why Don't I have 'this' context inside of a .then() in my Ember component

我是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()我不能够调用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')
});

事情是,当您在其中写入function(){}时,范围会发生变化,而this将不会引用此组件。 这就是为什么在ES6的词汇概念this被引入。 这将保留this 因此,请改用Arrow函数,它将正常运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM