DIV CSS 佈局教程網

微信小程序引入第三方庫 Immutable.js 的實作詳解
編輯:關於JavaScript     

前言

Immutable.js 提供了一個惰性 Sequence,允許高效率的鏈式方法呼叫,像 map、filter 等,不必建立中間的暫存物件。它透過惰性佇列與雜湊映射,提供了 Sequence、Range、Repeat、Map、OrderedMap、Set 以及一個稀疏 Vector。

微信小程序同樣無法直接透過 require('immutable.js') 呼叫,需要先對下載的程式碼做一點修改才能使用。

原因分析

Immutable 採用了 UMD 模組化規範

 (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Immutable = factory()); }(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; .... }));

UMD 的實現很簡單:先判斷是否支援 Node.js(CommonJS)規範,有的話就用 CommonJS 方式載入;再判斷是否支援 AMD,有的話就用 AMD 方式;兩者都不存在時,就把模組掛到全域。而以 CommonJS 載入的前提,是 exports 與 module 都必須有定義。經測試,微信小程序的運行環境裡這兩者並未定義。

解決方法

修改 Immutable 的程式碼,註解掉原有的模組導出語句,改用 module.exports = factory() 強制導出。

 (function(global, factory) { /* typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Immutable = factory()); */ module.exports = factory(); }(this, function() {

使用 Immutable.js

 //index.js var Immutable = require( '../../libs/immutable/immutable.modified.js' ); //獲取應用實例 var app = getApp(); Page( { onLoad: function() { //console.log('onLoad'); var that = this; var lines = []; lines.push( "var map1 = Immutable.Map({a:1, b:2, c:3});" ); var map1 = Immutable.Map({a:1, b:2, c:3}); lines.push( "var map2 = map1.set('b', 50);" ); var map2 = map1.set('b', 50); lines.push( "map1.get('b');" ); lines.push(map1.get('b')); lines.push( "map2.get('b');" ); lines.push(map2.get('b')); this.setData( { text: lines.join( '\n' ) }) } })

總結

從範例不難看出 Immutable 資料結構的特性:呼叫 set 不會改動原本的 map1,而是回傳一個新的 map2,這正是「不可變」資料的價值所在。掌握這個改造技巧後,就能在小程序中靈活運用各種成熟的第三方庫。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved