通过'这个'在类ecmascript中回调6

时间:2016-04-24 07:14:27

标签: javascript callback ecmascript-6 this

我在ecmascript 6中有一个班级。我需要传递一个'这个'回调。

我尝试使用.bind(this)。到目前为止似乎没有用。我也尝试过设置var _this = this;并在回调中使用_this。它仍然无效

     class Modal {
        constructor(modal) {
        this._modal = modal;
        this.id = this._options.id;      
       }
    }

    open(opts) {
        let modalOptions = {
            size: opts.size || '',
                templateUrl: 'modal.html',
                controller: function controller($scope, $uibModalInstance) {
                    var _this = this; 
                    this._options = {
                        id: opts.id
                    };
                    this.hcbuttons: [{id: '1', name: 'test'}, {id: '2', name: 'abc'}];
                    publisher.subscribe('triggered', this._options.id, function(event, creator) {
                        //as soon as we subscribe to the published event
                        var result = this.hcbuttons.filter(function( obj ) {
                            return obj.id == creator;
                        })[0];
                        if(result.sync === true) {
                            console.log('disabledall');
                        }                         
                    }).bind(this);


        }

} 

2 个答案:

答案 0 :(得分:3)

你错误地绑定了this。您正在调用subscribe函数的返回值上的绑定。 Function 对象的原型中只有bind函数。因此,您的代码可能会从}).bind(this);转移到}.bind(this))

由于您想将this设置为模态类,

 //change one
 open(opts) {
        var _this = this;
        let modalOptions = {
 //~~~~~~~~~~~~~~~~~~~~~~~~~~~
 //change two
 }.bind(_this));

答案 1 :(得分:2)

如果您使用的是ES2015,为什么不使用 lambdas (箭头功能)?他们自动绑定

open(opts) {
  let modalOptions = {
    size: opts.size || '',
    templateUrl: 'modal.html',
    controller: function controller($scope, $uibModalInstance) {
      this._options = {
        id: opts.id
      };
      this.hcbuttons = [{
        id: '1',
        name: 'test'
      }, {
        id: '2',
        name: 'abc'
      }];
      publisher.subscribe('triggered', this._options.id, (event, creator) => {
        let result = this.hcbuttons.filter(obj => obj.id === creator)[0];
        if (result.sync) {
          console.log('disabledall');
        }
      });
    }
  }
}

在这里,您可以阅读有关箭头功能的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions以及它们的工作原理(将来可能会对您有所帮助)。

相关问题