【问题标题】:Is there any other elegant way to do function binding? [duplicate]还有其他优雅的方法来进行函数绑定吗? [复制]
【发布时间】:2015-12-12 23:16:44
【问题描述】:

我的项目使用 ES6 类语法、React.js 和 Flux。 这是一段代码:

export default class Splash extends React.Component {

  constructor() {
    super();
    this.state = Comm.reqSplash();
  }

  componentDidMount(){
    this._appReadyBound = this._appReady.bind(this);
    SplashStore.subscribe(this._appReadyBound);
  }

  //Trigger when app data is loaded, if splash is in non-intro mode then end splash
  _appReady(){
    SplashStore.unsubscribe(this._appReadyBound);
    //If intro mode, do nothing
    if (this.state.mode !== "non-intro") return;
    this.endSplash();
  }
}

如您所见,在“componentDidMount”方法中,我必须创建“_appReady”方法的绑定版本。

如果我不绑定“this”,“_appReady”方法将无法正常运行。如果我不做绑定版本,unsubscribe方法,如果你更熟悉的话,和“removeChangeListener”一样,不会做它的工作,这意味着监听器还在监听器列表中。

所以我想知道是否有一种优雅的方式来做绑定,或者避免绑定。或者我应该放弃 ES6 类语法?

【问题讨论】:

标签: javascript reactjs bind ecmascript-6 flux


【解决方案1】:

你试过了吗

_appready = () => {
  //function here

}

希望对你有帮助

【讨论】:

  • 那应该是什么/在哪里?
  • 它应该替换 appready 函数,用箭头编写的 es6 方式应该给出所需的内部 this 范围。
  • 这不是有效的 ES6。你不能把它放在类体内。
猜你喜欢
  • 1970-01-01
  • 2012-10-08
  • 2011-04-21
  • 2023-02-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
  • 2010-11-12
  • 2011-10-19
相关资源
最近更新 更多