在类方法的jQuery事件回调中调用另一个类方法的问题
解决jQuery事件回调中无法调用类方法的问题
我明白你碰到的麻烦了——在jQuery的事件回调函数里,this默认会指向触发事件的DOM元素,而不是你的类实例,所以直接用this.onSimulate()肯定会失败。这里有几个实用的解决方案,你可以根据自己的代码风格选择:
方法1:提前保存类实例的引用
在方法开头把类实例的this存到一个变量里(比如self或者that),然后在回调里用这个变量调用类方法。这种方法兼容性最好,老浏览器也支持:
jqueryNextDataEditableShow() { const self = this; // 保存类实例的引用 $('#symbolTable .editable').on('hidden', function (e, reason) { if (reason === 'save' || reason === 'nochange') { var $next = $(this).closest('td').next().find('.editable'); if($next != undefined && $next.length == 0){ self.onSimulate(); // 用保存的self调用类方法 } setTimeout(function () { $next.editable('show'); }, 300); } }); }
方法2:使用ES6箭头函数
箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的类实例)。不过要注意,这时候回调里的this不再是DOM元素了,你需要通过e.target来获取触发事件的元素:
jqueryNextDataEditableShow() { $('#symbolTable .editable').on('hidden', (e, reason) => { if (reason === 'save' || reason === 'nochange') { var $next = $(e.target).closest('td').next().find('.editable'); if($next != undefined && $next.length == 0){ this.onSimulate(); // 现在this指向类实例 } setTimeout(() => { $next.editable('show'); }, 300); } }); }
方法3:用bind()绑定回调的this
你可以把回调函数单独定义,然后用bind(this)把类实例绑定到回调的this上。这种方法适合需要复用回调函数的场景:
jqueryNextDataEditableShow() { const handleHidden = function(e, reason) { if (reason === 'save' || reason === 'nochange') { var $next = $(e.target).closest('td').next().find('.editable'); if($next != undefined && $next.length == 0){ this.onSimulate(); // 这里的this是类实例 } setTimeout(function () { $next.editable('show'); }, 300); } }.bind(this); // 绑定类实例到回调函数 $('#symbolTable .editable').on('hidden', handleHidden); }
这三种方法都能帮你在回调里成功调用onSimulate(),选哪个看你个人习惯和项目的ES版本支持情况就好~
内容的提问来源于stack exchange,提问作者Yash Jain
相关产品推荐
相关产品推荐

