|
| 1 | +/* |
| 2 | + * // 1. 在 app.js 中引入此文件 |
| 3 | + * require('mixin.js') |
| 4 | + * |
| 5 | + * // 2. 撰写一个 testMixin.js |
| 6 | + * module.exports = { |
| 7 | + * data: { someData: 'testMixin' }, |
| 8 | + * onShow () { console.log('Log from mixin!') } |
| 9 | + * } |
| 10 | + * |
| 11 | + * // 3. 在页面 page/index/index.js 引入 |
| 12 | + * const testMixin = require('testMixin.js') |
| 13 | + * Page({ |
| 14 | + * mixins: [testMixin] |
| 15 | + * }) |
| 16 | + */ |
| 17 | + |
| 18 | +const originPage = Page; |
| 19 | +const originComponent = Component; |
| 20 | + |
| 21 | +const originProperties = ['data', 'properties', 'options']; |
| 22 | +const originMethods = [ |
| 23 | + 'onLoad', |
| 24 | + 'onReady', |
| 25 | + 'onShow', |
| 26 | + 'onHide', |
| 27 | + 'onUnload', |
| 28 | + 'onPullDownRefresh', |
| 29 | + 'onReachBottom', |
| 30 | + 'onShareAppMessage', |
| 31 | + 'onPageScroll', |
| 32 | + 'onTabItemTap' |
| 33 | +]; |
| 34 | + |
| 35 | +function merge(mixins, config) { |
| 36 | + if (!Array.isArray(mixins)) return; |
| 37 | + mixins.forEach(mixinItem => { |
| 38 | + if (Object.prototype.toString.call(mixinItem) !== '[object Object]') { |
| 39 | + throw new Error(`mixin type must be Object`); |
| 40 | + } |
| 41 | + for (let [key, value] of Object.entries(mixinItem)) { |
| 42 | + if (originProperties.includes(key)) { |
| 43 | + config[key] = { ...value, ...config[key] }; |
| 44 | + } else if (originMethods.includes(key)) { |
| 45 | + const originFunction = config[key]; |
| 46 | + config[key] = function(...args) { |
| 47 | + value.call(this, ...args); |
| 48 | + return originFunction && originFunction.call(this, ...args); |
| 49 | + }; |
| 50 | + } else { |
| 51 | + config = { ...config, ...mixinItem }; |
| 52 | + } |
| 53 | + } |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +Page = config => { |
| 58 | + if (Array.isArray(config.mixins)) { |
| 59 | + config = merge(config, config.mixins); |
| 60 | + } |
| 61 | + originPage(config); |
| 62 | +}; |
| 63 | + |
| 64 | +Component = config => { |
| 65 | + if (Array.isArray(config.mixins)) { |
| 66 | + config = merge(config, config.mixins); |
| 67 | + } |
| 68 | + originComponent(config); |
| 69 | +}; |
0 commit comments