簡體   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