// behavior.jsmodule.exports = Behavior({definitionFilter(defFields) {defFields.data.from = 'behavior'},})// component.jsComponent({data: {from: 'component'},behaviors: [require('behavior.js')],ready() {console.log(this.data.from) // 此处会发现输出 behavior 而不是 component}})
data
定义段里的内容。Behavior()
构造器提供了新的定义段definitionFilter
,用于支持自定义组件扩展。definitionFilter
是一个函数,在被调用时会注入两个参数,第一个参数是使用该 behavior 的 component/behavior 的定义对象,第二个参数是该 behavior 所使用的 behavior 的definitionFilter
函数列表。// behavior3.jsmodule.exports = Behavior({definitionFilter(defFields, definitionFilterArr) {},})// behavior2.jsmodule.exports = Behavior({behaviors: [require('behavior3.js')],definitionFilter(defFields, definitionFilterArr) {// definitionFilterArr[0](defFields)},})// behavior1.jsmodule.exports = Behavior({behaviors: [require('behavior2.js')],definitionFilter(defFields, definitionFilterArr) {},})// component.jsComponent({behaviors: [require('behavior1.js')],})
definitionFilter
定义段。那么按照声明的顺序会有如下事情发生:definitionFilter
函数,其中defFields
参数是 behavior2 的定义段,definitionFilterArr
参数即为空数组,因为 behavior3 没有使用其他的 behavior 。definitionFilterArr
参数是一个长度为1的数组,definitionFilterArr[0]
即为 behavior3 的definitionFilter
函数,因为 behavior2 使用了 behavior3。用户在此处可以自行决定在进行 behavior1 的声明时要不要调用 behavior3 的definitionFilter
函数,如果需要调用,在此处补充代码definitionFilterArr[0](defFields)
即可,definitionFilterArr
参数会由基础库补充传入。definitionFilter
函数。definitionFilter
函数可以理解为当 A 使用了 B 时,A 声明就会调用 B 的definitionFilter
函数并传入 A 的定义对象让 B 去过滤。此时如果 B 还使用了 C 和 D ,那么 B 可以自行决定要不要调用 C 和 D 的definitionFilter
函数去过滤 A 的定义对象。// behavior.jsmodule.exports = Behavior({lifetimes: {created() {this._originalSetData = this.setData // 原始 setDatathis.setData = this._setData // 封装后的 setData}},definitionFilter(defFields) {const computed = defFields.computed || {}const computedKeys = Object.keys(computed)const computedCache = {}// 计算 computedconst calcComputed = (scope, insertToData) => {const needUpdate = {}const data = defFields.data = defFields.data || {}for (const key of computedKeys) {const value = computed[key].call(scope) // 计算新值if (computedCache[key] !== value) needUpdate[key] = computedCache[key] = valueif (insertToData) data[key] = needUpdate[key] // 直接插入到 data 中,初始化时才需要的操作}return needUpdate}// 重写 setData 方法defFields.methods = defFields.methods || {}defFields.methods._setData = function (data, callback) {const originalSetData = this._originalSetData // 原始 setDataoriginalSetData.call(this, data, callback) // 做 data 的 setDataconst needUpdate = calcComputed(this) // 计算 computedoriginalSetData.call(this, needUpdate) // 做 computed 的 setData}// 初始化 computedcalcComputed(defFields, true) // 计算 computed}})
const beh = require('./behavior.js')Component({behaviors: [beh],data: {a: 0,},computed: {b() {return this.data.a + 100},},methods: {onTap() {this.setData({a: ++this.data.a,})}}})
<view>data: {{a}}</view><view>computed: {{b}}</view><button bindtap="onTap">click</button>
本页内容是否解决了您的问题?