溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

小程序開發(fā)中如何使用Underscore.js

發(fā)布時(shí)間:2021-01-26 11:55:39 來源:億速云 閱讀:265 作者:小新 欄目:移動開發(fā)

這篇文章主要介紹小程序開發(fā)中如何使用Underscore.js,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

前言

Underscore.js是一個(gè)很精干的庫,壓縮后只有4KB。Underscore 提供了100多個(gè)函數(shù),包括常用的:map、filter、invoke — 當(dāng)然還有更多專業(yè)的輔助函數(shù),如:函數(shù)綁定、JavaScript 模板功能、創(chuàng)建快速索引、強(qiáng)類型相等測試等等。彌補(bǔ)了標(biāo)準(zhǔn)庫的不足,大大方便了JavaScript的編程。

微信小程序無法直接使用require( 'underscore.js' )進(jìn)行調(diào)用。

微信小程序模塊化機(jī)制

微信小程序運(yùn)行環(huán)境支持CommoJS模塊化,通過module.exports暴露對象,通過require來獲取對象。

微信小程序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模塊導(dǎo)出代碼如下:

// 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必須都有定義,才能導(dǎo)出。通過測試,微信小程序運(yùn)行環(huán)境exports、module并沒有定義

//index.js

//獲取應(yīng)用實(shí)例
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); 
 }
})

小程序開發(fā)中如何使用Underscore.js

解決方法

修改Underscore代碼,注釋原有模塊導(dǎo)出語句,使用module.exports = _ 強(qiáng)制導(dǎo)出

 /*
 // 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' );

//獲取應(yīng)用實(shí)例
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' )
 })
 }
})

小程序開發(fā)中如何使用Underscore.js

以上是“小程序開發(fā)中如何使用Underscore.js”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI