微信小程序使用第三方库Underscore.js步骤详解


Posted in Javascript onSeptember 27, 2016

前言

Underscore.js是一个很精干的库,压缩后只有4KB。Underscore 提供了100多个函数,包括常用的:map、filter、invoke — 当然还有更多专业的辅助函数,如:函数绑定、JavaScript 模板功能、创建快速索引、强类型相等测试等等。弥补了标准库的不足,大大方便了JavaScript的编程。

微信小程序无法直接使用require( 'underscore.js' )进行调用。

微信小程序模块化机制

微信小程序运行环境支持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模块导出代码如下:

// 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.js步骤详解

解决方法

修改Underscore代码,注释原有模块导出语句,使用module.exports = _ 强制导出

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

微信小程序使用第三方库Underscore.js步骤详解

总结

以上就是微信小程序使用第三方库Underscore.js的全部内容,希望对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。

Javascript 相关文章推荐
jquery实现弹出窗口效果的实例代码
Nov 28 Javascript
jQuery中ajax的post()方法用法实例
Dec 26 Javascript
详解JavaScript中void语句的使用
Jun 04 Javascript
JS组件Bootstrap Table表格多行拖拽效果实现代码
Dec 08 Javascript
使用vuex缓存数据并优化自己的vuex-cache
May 30 Javascript
vue-router 实现导航守卫(路由卫士)的实例代码
Sep 02 Javascript
vue实现微信二次分享以及自定义分享的示例
Mar 20 Javascript
javascript数据类型中的一些小知识点(推荐)
Apr 18 Javascript
JavaScript 格式化数字、金额、千分位、保留几位小数、舍入舍去
Jul 23 Javascript
vue 实现特定条件下绑定事件
Nov 09 Javascript
微信小程序pinker组件使用实现自动相减日期
May 07 Javascript
浅谈克隆 JavaScript
Nov 02 Javascript
微信小程序使用第三方库Immutable.js实例详解
Sep 27 #Javascript
微信小程序 在Chrome浏览器上运行以及WebStorm的使用
Sep 27 #Javascript
微信小程序 开发指南详解
Sep 27 #Javascript
纯JavaScript 实现flappy bird小游戏实例代码
Sep 27 #Javascript
jQuery实现表格文本框淡入更改值后淡出效果
Sep 27 #Javascript
angular基于路由控制ui-router实现系统权限控制
Sep 27 #Javascript
IOS中safari下的select下拉菜单文字过长不换行的解决方法
Sep 26 #Javascript
You might like
php获取本机真实IP地址实例代码
2016/03/31 PHP
php打乱数组二维数组多维数组的简单实例
2016/06/17 PHP
PHP基于mssql扩展远程连接MSSQL的简单实现方法
2016/10/08 PHP
TP5(thinkPHP5框架)基于bootstrap实现的单图上传插件用法示例
2019/05/29 PHP
php使用fputcsv实现大数据的导出操作详解
2020/02/27 PHP
PHP连接MySQL数据库操作代码实例解析
2020/07/11 PHP
JavaScript使用prototype定义对象类型(转)[
2006/12/22 Javascript
JavaScript常用对象的方法和属性小结
2012/01/24 Javascript
如何使用JS获取IE上传文件路径(IE7,8)
2013/07/08 Javascript
js中传递特殊字符(+,&)的方法
2014/01/16 Javascript
HTML+CSS+JS实现完美兼容各大浏览器的TABLE固定列
2015/04/26 Javascript
JS中处理时间之setUTCMinutes()方法的使用
2015/06/12 Javascript
微信JSSDK上传图片
2015/08/23 Javascript
在ASP.NET MVC项目中使用RequireJS库的用法示例
2016/02/15 Javascript
JS组件Bootstrap Table使用实例分享
2016/05/30 Javascript
EasyUI加载完Html内容样式渲染完成后显示
2016/07/25 Javascript
微信小程序实现横向增长表格的方法
2018/07/24 Javascript
vue实现点击选中,其他的不选中方法
2018/09/05 Javascript
深入理解react 组件类型及使用场景
2019/03/07 Javascript
在vue中使用防抖函数组件操作
2020/07/26 Javascript
原生js实现滑块区间组件
2021/01/20 Javascript
跟老齐学Python之赋值,简单也不简单
2014/09/24 Python
Python连接phoenix的方法示例
2017/09/29 Python
pycharm下打开、执行并调试scrapy爬虫程序的方法
2017/11/29 Python
python 并发下载器实现方法示例
2019/11/22 Python
python3注册全局热键的实现
2020/03/22 Python
利用pandas向一个csv文件追加写入数据的实现示例
2020/04/23 Python
Python正则表达式高级使用方法汇总
2020/06/18 Python
基于Python的接口自动化unittest测试框架和ddt数据驱动详解
2021/01/27 Python
沙特阿拉伯网上购物:Sayidaty Mall
2018/05/06 全球购物
求职信怎么写范文
2014/05/26 职场文书
海上钢琴师观后感
2015/06/03 职场文书
法人身份证明书
2015/06/18 职场文书
初中体育课教学反思
2016/02/16 职场文书
vue实现列表拖拽排序的示例代码
2022/04/08 Vue.js
python数字图像处理之图像的批量处理
2022/06/28 Python