抖音(字节跳动)小程序不支持微信小程序中的 observers 的替代方案

今天遇到个需求,需要在组件中对 properties 数据进行监听,如果 properties 数据改变的话,就执行相应的回调函数。

在微信小程序中,我们可以在组件的构造对象中定义 observers 字段对数据进行监听。

Component({
  attached: function() {
    this.setData({
      numberA: 1,
      numberB: 2,
    })
  },
  observers: {
    'numberA, numberB': function(numberA, numberB) {
      // 在 numberA 或者 numberB 被设置时,执行这个函数
      this.setData({
        sum: numberA + numberB
      })
    }
  }
})

 而在抖音小程序中,并没有提供 observers,而是提供了和 observers 类似的特性。

对应的官方文档看这里:Component 构造器

 我们可以在某个 properties 数据的定义对象中定义对应的 observer 回调函数。当该 properties  数据发生变化的时候,会触发执行该回调函数。

Component({
  behaviors: [],

  properties: {
    myProperty: {
      // Type (required), currently accepted types include: String, Number, Boolean, Object, Array, null (indicating any type)
      type: String,
      // The initial value of the attribute (optional), if not specified, one will be selected according to the type
      value: '',
      // The function (optional) executed when the property is changed can also be written as the method name string defined in the methods section, such as:'_myPropertyChange'
      observer: function(newVal, oldVal) {
         // Usually newVal is the newly set data, oldVal is the old data
      }
    },
    myPropertyB: String // Simplified definition
  }
})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值