Uncaught TypeError报错:为何无法访问EditorView中的saveValue函数?
问题原因及解决办法
报错原因
你在control_select.on('change', function(e) { ... })里用普通函数当回调时,函数内部的this指向的是触发change事件的DOM元素(也就是你的select2下拉框),根本不是EditorView的实例对象。所以调用this.saveValue()时,自然找不到这个方法,就会抛出TypeError。
三种修复方案
方案一:用箭头函数(推荐)
箭头函数不会绑定自己的this,会直接继承外层作用域的this(也就是onReady里的EditorView实例):
var EditorView = elementor.modules.controls.BaseData.extend({ onReady() { this.control_select = this.$el.find('.js-example-basic-multiple'); this.control_select.select2({}); // 替换成箭头函数 this.control_select.on('change', (e) => { this.saveValue(); }); }, saveValue() { this.setValue(this.control_select.val()); }, onBeforeDestroy() { this.saveValue(); this.ui.textarea[0].emojioneArea.off(); } });
方案二:提前把实例的this存成变量
在onReady里先把实例的this存成一个变量(比如self),回调里用这个变量调用方法:
var EditorView = elementor.modules.controls.BaseData.extend({ onReady() { const self = this; // 保存实例的this this.control_select = this.$el.find('.js-example-basic-multiple'); this.control_select.select2({}); this.control_select.on('change', function (e) { self.saveValue(); // 用self调用实例方法 }); }, saveValue() { this.setValue(this.control_select.val()); }, onBeforeDestroy() { this.saveValue(); this.ui.textarea[0].emojioneArea.off(); } });
方案三:用bind绑定this
通过bind方法把回调函数的this强制绑定为EditorView实例:
var EditorView = elementor.modules.controls.BaseData.extend({ onReady() { this.control_select = this.$el.find('.js-example-basic-multiple'); this.control_select.select2({}); this.control_select.on('change', function (e) { this.saveValue(); }.bind(this)); // 绑定this到实例 }, saveValue() { this.setValue(this.control_select.val()); }, onBeforeDestroy() { this.saveValue(); this.ui.textarea[0].emojioneArea.off(); } });
内容的提问来源于stack exchange,提问作者user19657936
相关产品推荐
相关产品推荐

