Home  >  Article  >  WeChat Applet  >  Code examples using Immutable.js for small program development

Code examples using Immutable.js for small program development

Y2J
Y2JOriginal
2017-05-05 11:27:351895browse

Immutable 是 Facebook 开发的不可变数据集合。不可变数据一旦创建就不能被修改,是的应用开发更简单,允许使用函数式编程技术,比如惰性评估。Immutable JS 提供一个惰性 Sequence,允许高效的队列方法链,类似 map 和 filter ,不用创建中间代表。immutable 通过惰性队列和哈希映射提供 Sequence, Range, Repeat, Map, OrderedMap, Set 和一个稀疏 Vector。

微信小程序无法直接使用require( 'immutable.js' )进行调用,需要对下载的Immutable代码进行修改,才能使用。

原因分析

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)模块规范,存在则使用Node.js(CommonJS)方式加载模块。再判断是否支持AMD,存在则使用AMD方式加载模块。前两个都不存在,则将模块公开到全局。

exports、module必须都有定义,才能以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' )
        })
    }
})

Code examples using Immutable.js for small program development

【相关推荐】

1. 微信小程序完整源码

2. 微信小程序demo:仿网易云音乐

The above is the detailed content of Code examples using Immutable.js for small program development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn