微信小程序 框架扩展MobX绑定辅助库


当前第2页 返回上一页

注意:你可以用 Component 构造器构造页面, 参考文档 。

import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    /* 绑定配置(见下文) */
  }
})

手工绑定

手工绑定 适用于全部场景。做法:使用 createStoreBindings 创建绑定,它会返回一个包含清理函数的对象用于取消绑定。

注意:在页面 onUnload (自定义组件 detached )时一定要调用清理函数,否则将导致内存泄漏!

import { createStoreBindings } from 'mobx-miniprogram-bindings'

Page({
  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      /* 绑定配置(见下文) */
    })
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  }
})

绑定配置

无论使用哪种绑定方式,都必须提供一个绑定配置对象。这个对象包含的字段如下:

字段名类型含义
store一个 MobX observable默认的 MobX store
fields数组或者对象用于指定需要绑定的 data 字段
actions数组或者对象用于指定需要映射的 actions

fields

fields 有三种形式:

  • 数组形式:指定 data 中哪些字段来源于 store 。例如 ['numA', 'numB', 'sum'] 。
  • 映射形式:指定 data 中哪些字段来源于 store 以及它们在 store 中对应的名字。例如 { a: 'numA', b: 'numB' } ,此时 this.data.a === store.numA this.data.b === store.numB 。
  • 函数形式:指定 data 中每个字段的计算方法。例如 { a: () => store.numA, b: () => anotherStore.numB } ,此时 this.data.a === store.numA this.data.b === anotherStore.numB 。

上述三种形式中,映射形式和函数形式可以在一个配置中同时使用。

如果仅使用了函数形式,那么 store 字段可以为空,否则 store 字段必填。

actions

actions 可以用于将 store 中的一些 actions 放入页面或自定义组件的 this 下,来方便触发一些 actions 。有两种形式:

  • 数组形式:例如 ['update'] ,此时 this.update === store.update 。
  • 映射形式:例如 { buttonTap: 'update' } ,此时 this.buttonTap === store.update 。

只要 actions 不为空,则 store 字段必填。

延迟更新与立刻更新

为了提升性能,在 store 中的字段被更新后,并不会立刻同步更新到 this.data 上,而是等到下个 wx.nextTick 调用时才更新。(这样可以显著减少 setData 的调用次数。)

如果需要立刻更新,可以调用:

  • this.updateStoreBindings() (在 behavior 绑定 中)
  • this.storeBindings.updateStoreBindings() (在 手工绑定 中)



标签:微信小程序

返回前面的内容

相关阅读 >>

微信小程序 api

微信小程序api 地图-创建mapcontext对象

微信小程序 页面路由

微信小程序api 背景音频-控制播放进度

微信小程序 javascript支持情况

微信小程序api 动画

微信小程序云开发 第一个云开发小程序

微信小程序 sitemap配置

微信小程序 weuicell

微信小程序 全局配置

更多相关阅读请进入《微信小程序》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...