微信小程序開發實戰——使用Underscore.js

Underscore.js 是一個 JavaScript 工具庫,它提供了一整套函數式編程的實用功能,可是沒有擴展任何 JavaScript 內置對象。Underscore 提供了100多個函數,包括經常使用的:map、filter、invoke — 固然還有更多專業的輔助函數,如:函數綁定、JavaScript 模板功能、建立快速索引、強類型相等測試等等。 微信小程序沒法直接使用require( 'underscore.js' )進行調用。git

微信小程序模塊化機制

微信小程序運行環境支持CommoJS模塊化,經過module.exports暴露對象,經過require來獲取對象。github

微信小程序Quick Start utils/util.js編程

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds();


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

pages/log/log.js小程序

var util = require('../../utils/util.js')
Page({
  data: {
    logs: []
  },
  onLoad: function () {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(function (log) {
        return util.formatTime(new Date(log))
      })
    })
  }
})

緣由分析

Underscore CommonJs模塊導出代碼以下:微信小程序

// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
  if (typeof module !== 'undefined' && module.exports) {
     exports = module.exports = _;
  }
  exports._ = _;
} else {
  root._ = _;
}

exports、module必須都有定義,才能導出。經過測試,微信小程序運行環境exports、module並無定義微信

//index.js

//獲取應用實例
var app = getApp();

Page({ 

  onLoad: function () {
    console.log('onLoad');
    var that = this;

    console.log('typeof exports: ' + typeof exports);    
    console.log('typeof module: ' + typeof exports); 

    var MyClass = function() {

    }

    module.exports = MyClass;

    console.log('typeof module.exports: ' + typeof module.exports);   
  }
})

圖片描述

解決方法

修改Underscore代碼,註釋原有模塊導出語句,使用module.exports = _ 強制導出app

/*
    // Export the Underscore object for **Node.js**, with
    // backwards-compatibility for the old `require()` API. If we're in
    // the browser, add `_` as a global object.
    if (typeof exports !== 'undefined') {
      if (typeof module !== 'undefined' && module.exports) {
        exports = module.exports = _;
      }
      exports._ = _;
    } else {
      root._ = _;
    }
    */

    module.exports = _;
/*
    // AMD registration happens at the end for compatibility with AMD loaders
    // that may not enforce next-turn semantics on modules. Even though general
    // practice for AMD registration is to be anonymous, underscore registers
    // as a named module because, like jQuery, it is a base library that is
    // popular enough to be bundled in a third party lib, but not be part of
    // an AMD load request. Those cases could generate an error when an
    // anonymous define() is called outside of a loader request.
    if (typeof define === 'function' && define.amd) {
      define('underscore', [], function() {
        return _;
      });
    }
    */

使用Underscore.js

//index.js

var _ = require( '../../libs/underscore/underscore.modified.js' );

//獲取應用實例
var app = getApp();


Page( {

    onLoad: function() {
        //console.log('onLoad');
        var that = this;

        var lines = [];

        lines.push( "_.map([1, 2, 3], function(num){ return num * 3; });" );
        lines.push( _.map( [ 1, 2, 3 ], function( num ) { return num * 3; }) );

        lines.push( "var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);" );
        lines.push( _.reduce( [ 1, 2, 3 ], function( memo, num ) { return memo + num; }, 0 ) );

        lines.push( "var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });" );
        lines.push( _.find( [ 1, 2, 3, 4, 5, 6 ], function( num ) { return num % 2 == 0; }) );

        lines.push( "_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });" );
        lines.push( _.sortBy( [ 1, 2, 3, 4, 5, 6 ], function( num ) { return Math.sin( num ); }) );

        lines.push( "_.indexOf([1, 2, 3], 2);" );
        lines.push( _.indexOf([1, 2, 3], 2) );

        this.setData( {
            text: lines.join( '\n' )
        })
    }
})

圖片描述

其餘

完整代碼 https://github.com/guyoung/Gy...ide

相關文章
相關標籤/搜索