如何在JavaScript的onreadystatechange函数内调用Polymer对话框?
解决Polymer中XMLHttpRequest回调里this指向问题的方案
兄弟,你碰到的是JavaScript里经典的作用域/this指向坑!在onreadystatechange这个回调函数内部,this并不是指向你的Polymer组件实例,而是指向toQueueRequest这个XMLHttpRequest对象,所以自然找不到this.$.processingDialog啦。给你三个靠谱的解决办法:
方法1:提前保存组件的this到变量
最传统也最稳妥的方式,在回调外面把组件的this存到一个变量里(比如that或者self),回调里用这个变量代替this:
// 先把组件实例的this存起来 const that = this; toQueueRequest.onreadystatechange = function () { if (toQueueRequest.readyState === 4 && toQueueRequest.status === 200) { that.$.processingDialog.close(); that.$.confirmDialog.open(); } else if (toQueueRequest.readyState === 4){ that.$.processingDialog.close(); that.$.errorMsg = "Ha ocurrido un error!"; that.$.errorDialog.open(); } }; // 后面的发送请求代码不变 if (this.sector == "Cualquiera") {this.sector = null;}; var data = JSON.stringify({"RestoCode": restoCode, "Fingerprint": finger, "PhoneNumber": this.cellno, "PersonalName": this.name, "QuantityPeople": this.pas, "SectorId": this.sector}); toQueueRequest.send(data); this.$.reviewDialog.close(); this.$.processingDialog.open();
方法2:使用ES6箭头函数
箭头函数不会创建自己的this,它会继承外层作用域的this,也就是你的Polymer组件实例,代码更简洁:
toQueueRequest.onreadystatechange = () => { if (toQueueRequest.readyState === 4 && toQueueRequest.status === 200) { this.$.processingDialog.close(); this.$.confirmDialog.open(); } else if (toQueueRequest.readyState === 4){ this.$.processingDialog.close(); this.$.errorMsg = "Ha ocurrido un error!"; this.$.errorDialog.open(); } }; // 后续代码不变...
方法3:用bind()绑定this
把组件的this绑定到回调函数上,强制让回调里的this指向组件实例:
toQueueRequest.onreadystatechange = function () { if (toQueueRequest.readyState === 4 && toQueueRequest.status === 200) { this.$.processingDialog.close(); this.$.confirmDialog.open(); } else if (toQueueRequest.readyState === 4){ this.$.processingDialog.close(); this.$.errorMsg = "Ha ocurrido un error!"; this.$.errorDialog.open(); } }.bind(this); // 关键:绑定组件的this到回调 // 后续代码不变...
小提示
如果你的项目里允许用Polymer的内置组件,其实可以试试<iron-ajax>,它的回调函数默认会自动绑定组件实例的this,不用手动处理这些指向问题,会更省心哦~
内容的提问来源于stack exchange,提问作者Ignacio Nacho Parravicini
相关产品推荐
相关产品推荐

