将“this”传递给类 ECMASCRIPT 6 中的回调
pass 'this' to callback in a class ecmascript 6
我在 ecmascript 6 中有一个类。我需要将值"this"传递给回调。
我尝试使用.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);
}
}
您错误地绑定了this
。您正在通过函数的返回值调用绑定subscribe
。函数对象在其原型中仅具有函数bind
。因此,将您的代码从此}).bind(this);
到}.bind(this))
由于要this
设置为模态类,
//change one
open(opts) {
var _this = this;
let modalOptions = {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~
//change two
}.bind(_this));
如果您使用的是 ES2015,为什么不使用 lambda(箭头函数)?他们自动绑定它
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 以及它们的工作原理(将来可能会对您有所帮助)。
相关文章:
- AngularJS:我可以跳过函数参数回调吗
- 要求未定义JS回调参数
- MeteorJS:在带有回调的vzaar api上正确使用wrapAsync
- 自引用回调
- 测试Angular Service解决错误回调中的promise
- 如何将一个JavaScript函数回调为多个函数
- JavaScript回调函数
- 用于回调的javascript参数
- 将json回调数据转换为日期
- 承诺在非节点式回调上使用Bluebird
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- 如何使用jqueryAJAX从页面中回调多个变量
- jquery Onclick函数带有导致双击的回调排序函数
- Javascript点击事件回调不起作用
- 将“this”传递给类 ECMASCRIPT 6 中的回调
- 在PreSaveAction方法之后执行的ECMAScript回调方法
- 蒙戈.光标#映射(回调,[thisArg])与ECMAScript 6箭头函数
- 如何从Ecmascript 6(ES6)上类对象中的事件回调函数访问对象成员