登录  /  注册

小程序开发之详解使用Underscore.js

零下一度
发布: 2017-05-26 10:32:22
原创
2754人浏览过

大家都知道underscore.js是一个 javascript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 javascript 内置对象。那么这篇文章我们就来学习下微信小程序如何使用第三方库underscore.js,有需要的可以参考学习。

前言

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代码,注释原有模块导出语句,使用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的全部内容,希望对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。

【相关推荐】

1. 微信开发之如何调用全局JS?

2. 微信开发之JS动态修改样式

3. 微信开发之引用其他js文件实例详解

4. 微信开发之生命周期函数的实例教程

以上就是小程序开发之详解使用Underscore.js的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号