资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

小程序开发中如何使用Underscore.js

这篇文章主要介绍小程序开发中如何使用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.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”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


网页标题:小程序开发中如何使用Underscore.js
网页URL:http://cdkjz.cn/article/gdioih.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220