遇到的问题:
页面渲染时,调用后台服务,查询出的attrId是有数据的;渲染页面渲染完成后,在调试页面打断点,在全局变量this.attrId中保存了数据。
afterRender: function() { this.$('.js-rollback-reason').hide(); action.queryAttrIdByCode(this.attrCode).then(function(attrId) { this.attrId = attrId; }); },
但是在下面的方法中,使用this.attrId数据依然为null;
onRollbackClick: function() { var operContent = this.$('.js-text-form').val() || null; var workOrderIds = this.workOrderIds; var rollbackReason = this.$rollbackReason ? this.$rollbackReason.combobox('getSelectedItem') : ''; var reasonId = rollbackReason ? rollbackReason.actReasonId : ''; if (this.auditResult === '1') { action.checkInWorkOrder({ componentId: this.componentId, componentName: this.componentName, operContent: operContent, operAttrDtoList: [{ attrId: this.attrId, attrValue: this.auditResult }] }, workOrderIds[0]).then(function() { // 确认先调close函数,再弹出提示。 this.close(); fish.toast('success', res.CHECK_IN_WORK_ORDER_SUCCESS); }.bind(this)); } else { action.rollbackWorkOrder({ componentId: this.componentId, componentName: this.componentName, operContent: operContent, operAttrDtoList: [{ attrId: this.attrId, attrValue: this.auditResult }], rollbackReasonId: reasonId }, workOrderIds[0]).then(function() { // 确认先调close函数,再弹出提示。 this.close(); fish.toast('success', res.CHECK_IN_WORK_ORDER_SUCCESS); }.bind(this)); } },
解决问题:
后来发现是上面调用后台服务后,没有把数据绑定在this中,所以只需在调用后台服务后添加bind(this)即可;
afterRender: function() { this.$('.js-rollback-reason').hide(); action.queryAttrIdByCode(this.attrCode).then(function(attrId) { this.attrId = attrId; }.bind(this)); },
总结:
一般在一个函数中,如果使用了this,那么就在函数后加bind(this)