前言
Underscore.js是一个很精干的库,压缩后只有4KB。Underscore 提供了100多个函数,包括常用的:map、filter、invoke — 当然还有更多专业的辅助函数,如:函数绑定、JavaScript 模板功能、创建快速索引、强类型相等测试等等。弥补了标准库的不足,大大方便了JavaScript的编程。
微信小程序无法直接使用require( 'underscore.js' )进行调用。
微信小程序模块化机制
微信小程序运行环境支持CommoJS模块化,通过module.exports暴露对象,通过require来获取对象。
微信小程序Quick Start utils/util.js
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
原因分析
Underscore Commonjs模块导出代码如下:
exports、module必须都有定义,才能导出。通过测试,微信小程序运行环境exports、module并没有定义
//获取应用实例
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 = _
强制导出
module.exports = _;
使用Underscore.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,3 ],function( num ) { return num 3; }) );
lines.push( "var sum = _.reduce([1,function(memo,num){ return memo + num; },0);" );
lines.push( _.reduce( [ 1,function( memo,num ) { return memo + num; },0 ) );
lines.push( "var even = _.find([1,3,4,5,6],function(num){ return num % 2 == 0; });" );
lines.push( _.find( [ 1,6 ],function( num ) { return num % 2 == 0; }) );
lines.push( "_.sortBy([1,function(num){ return Math.sin(num); });" );
lines.push( _.sortBy( [ 1,function( num ) { return Math.sin( num ); }) );
lines.push( "_.indexOf([1,2);" );
lines.push( _.indexOf([1,2) );
this.setData( {
text: lines.join( '\n' )
})
}
})
总结
以上就是微信小程序使用第三方库Underscore.js的全部内容,希望对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。
原文地址:https://www.jb51.cc/weapp/45546.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。