jQuery——何时添加bind(this)

遇到的问题:

页面渲染时,调用后台服务,查询出的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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值