微信小程序使用第三方库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制作select列表双向选择示例代码
Sep 02 Javascript
浅谈document.write()输出样式
May 07 Javascript
基于Flowplayer打造一款免费的WEB视频播放器附源码
Sep 06 Javascript
jquery实现的回旋滚动效果完整实例【附demo源码下载】
Sep 20 Javascript
JS实现点击Radio动态更新table数据
Jul 18 Javascript
使用Node.js实现简易MVC框架的方法
Aug 07 Javascript
Vue-router 类似Vuex实现组件化开发的示例
Sep 15 Javascript
AngularJS遍历获取数组元素的方法示例
Nov 11 Javascript
vue 实现LED数字时钟效果(开箱即用)
Dec 08 Javascript
Vue 中使用lodash对事件进行防抖和节流操作
Jul 26 Javascript
Node.js path模块,获取文件后缀名操作
Nov 07 Javascript
如何理解Vue简单状态管理之store模式
May 15 Vue.js
微信小程序使用第三方库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
解析centos中Apache、php、mysql 默认安装路径
2013/06/25 PHP
PHP 实现代码复用的一个方法 traits新特性
2015/02/22 PHP
php防止sql注入的方法详解
2017/02/20 PHP
php实现支持中文的文件下载功能示例
2017/08/30 PHP
PHP中非常有用却鲜有人知的函数集锦
2019/08/17 PHP
Gambit vs CL BO3 第三场 2.13
2021/03/10 DOTA
js资料prototype 属性
2007/03/13 Javascript
js 设置选中行的样式的实现代码
2010/05/24 Javascript
jquery在项目中做复选框时遇到的一些问题笔记
2013/11/17 Javascript
Js中使用hasOwnProperty方法检索ajax响应对象的例子
2014/12/08 Javascript
JS实现文字向下滚动完整实例
2015/02/06 Javascript
在JavaScript中模拟类(class)及类的继承关系
2016/05/20 Javascript
Ubuntu系统下Angularjs开发环境安装
2016/09/01 Javascript
深入理解JS中的Function.prototype.bind()方法
2016/10/11 Javascript
微信小程序 MD5加密登录密码详解及实例代码
2017/01/12 Javascript
浅析JS中常用类型转换及运算符表达式
2017/07/23 Javascript
详解如何在vue项目中使用layui框架及采坑
2019/05/05 Javascript
微信小程序生成海报分享朋友圈的实现方法
2019/05/06 Javascript
使用Node.js在深度学习中做图片预处理的方法
2019/09/18 Javascript
如何优雅地在Node应用中进行错误异常处理
2019/11/25 Javascript
vue分页插件的使用方法
2019/12/25 Javascript
Django框架中render_to_response()函数的使用方法
2015/07/16 Python
实例解析Python的Twisted框架中Deferred对象的用法
2016/05/25 Python
Django框架表单操作实例分析
2019/11/04 Python
keras自定义损失函数并且模型加载的写法介绍
2020/06/15 Python
python中如何打包用户自定义模块
2020/09/23 Python
利用Pycharm + Django搭建一个简单Python Web项目的步骤
2020/10/22 Python
韩国家庭购物网上商店:Nsmall
2017/05/07 全球购物
SKECHERS斯凯奇中国官网:来自美国的运动休闲品牌
2018/11/14 全球购物
托管代码(Managed Code)和非托管代码(Unmanaged Code)有什么区别
2014/09/29 面试题
人力资源管理专业学生自我评价
2013/11/20 职场文书
大学生职业生涯规划书参考模板
2014/03/05 职场文书
在宿舍喝酒的检讨书
2014/09/28 职场文书
部门群众路线教育实践活动对照检查材料思想汇报
2014/10/07 职场文书
2014年培训工作总结范文
2014/11/27 职场文书
2019职场实习报告该怎么写?
2019/07/01 职场文书