【问题标题】:EmberJS Using Component in Different ContextEmberJS 在不同的上下文中使用组件
【发布时间】:2015-08-10 21:10:50
【问题描述】:

我正在尝试在 EmberJS 中使用不同的库 bootstrap-switch

我用.on('didInsertElement')添加了以下内容:

$(toggleTag).on('switchChange.bootstrapSwitch', function(event, state) {
      this.sendAction('updateAction', state);
});

但是,当调用此事件时,this 的上下文将为 html 元素 toggleTag 返回 object。相反,我需要为this 访问component

处理此问题的推荐方法是什么?

【问题讨论】:

    标签: javascript ember.js bootstrap-switch


    【解决方案1】:

    在 ES6 中使用 fat arrows 并继承父级的上下文(如果您使用的是 ember-cli,建议这样做):

    $(toggleTag).on('switchChange.bootstrapSwitch', (event, state) => {
      this.sendAction('updateAction', state);
    });
    

    在 ES5 中使用 bind 来修复函数上下文:

    $(toggleTag).on('switchChange.bootstrapSwitch', function(event, state){
      this.sendAction('updateAction', state);
    }.bind(this));
    

    或者保存上下文:

    var that = this;
    $(toggleTag).on('switchChange.bootstrapSwitch', function(event, state){
      that.sendAction('updateAction', state);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 1970-01-01
      • 2012-12-10
      • 2016-06-30
      • 2016-03-29
      • 2012-12-11
      • 2021-06-16
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多