首页 文章

EmberJS - 在承诺结算后调用超级行动

提问于
浏览
1

我使用的是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);
        })
     }
  }
});

在promises回调中调用时, this._super() 无法解析为父组件操作 . 我已经尝试将超级函数存储为属性并调用它:

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

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

我不知道该怎么办 . 谁能告诉我是否有一种干净的方式来做我想做的事情?任何意见,将不胜感激 . 非常感谢!

1 回答

  • 0

    在子组件中做:

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

相关问题