EmberJS - 在承诺解决后调用超级操作

EmberJS - Call super action after promise resolves

本文关键字:调用 超级操作 解决 承诺 EmberJS      更新时间:2023-09-26

我正在使用Ember 2.6.0

我正在扩展一个第三方组件,该组件在操作中定义了某些功能,我想在我的子类中捕获该操作,调用返回 promise 的函数并在 promise 解析时触发 supers 操作。

所以第三方组件这样做:

 import Ember from 'ember';
export default Ember.Component.extend({
  actions: {
     theAction() {
         this._somePrivateFunction();
        //do other stuff
     }
  }
});

在我的子类中,我正在做:

import Ember from 'ember';
import ThirdPartyComponent from 'path/to/component'
export default ThirdPartyComponent.extend({
  _funcThatReturnsPromise() {
     return new Ember.RSVP.Promise();
  }
  actions: {
     theAction() {
        const thePromise = this._funcThatReturnsPromise();
        thePromise.then(() => {
            // undefined!
            this._super(...arguments);
        })
     }
  }
});

在承诺回调中调用时,this._super()不会解析为父组件操作。我尝试将supers函数存储为属性并调用它:

   theAction() {
            const thePromise = this._funcThatReturnsPromise();
            this.set('superFunc', this._super);
            thePromise.then(() => {
           // calls the super but "this" inside the supers action is undefined
           this._super(...arguments);
       })
   }

这除了丑陋之外,还导致超动作内部的this未定义。我不知道为什么会这样..浏览一些文档。

还可以选择在我的子类操作中调用send()

   theAction() {
      const thePromise = this._funcThatReturnsPromise();
      this.set('superFunc', this._super);
      thePromise.then(() => {
          //infinite loop!
          this.send('theAction');
      });
   }

但这当然会导致无限循环,因为函数最终会调用自己。

我不确定如何在这里进行。谁能告诉我是否有一种干净的方式来做我在这里想做的事情?任何建议将不胜感激。多谢!

在子组件中,执行以下操作:

theAction() {
      const thePromise = this._funcThatReturnsPromise();
      let parentAction = this._super;
      let self = this;
      thePromise.then(() => {
          //parent usage
          parentAction();
          // this usage
          self.doSome();
      });
   }