Home >WeChat Applet >Mini Program Development >Detailed explanation of mini program development using Underscore.js

Detailed explanation of mini program development using Underscore.js

零下一度
零下一度Original
2017-05-26 10:32:223026browse

Everyone knows that Underscore.js is a JavaScript tool library that provides a set of practical functions for functional programming, but does not extend any JavaScript built-in objects. So in this article, we will learn how to use the third-party library Underscore.js in the WeChat applet. You can refer to it if necessary.

Preface

Underscore.js is a very lean library, only 4KB after compression. Underscore provides more than 100 functions, including commonly used ones: map, filter, invoke — and of course more professional auxiliary functions, such as: function binding, JavaScript template function, creating fast index, strong type Equality testing and more. It makes up for the shortcomings of the standard library and greatly facilitates JavaScript programming.

WeChat applet cannot be called directly using require( 'underscore.js' ).

WeChat Mini Program Modularization Mechanism

The WeChat Mini Program running environment supports CommoJS modularization and exposes objects through module.exports. Obtain objects through require.

WeChat Mini Program 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))
 })
 })
 }
})

Reason Analysis

Underscore CommonJs module export code is as follows:

// 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 and module must both be defined before they can be exported. Through testing, the WeChat applet running environment exports and modules are not defined

//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); 
 }
})

##Solution

Modify the Underscore code,

CommentsFor the original module export statement, use module.exports = _ Forced export

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

Use 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' )
 })
 }
})

Summary

The above is all about WeChat applet using the third-party library Underscore.js The content, I hope it will be helpful to everyone’s study or work. If you have any questions, you can leave a message to communicate.

[Related recommendations]

1.

How to call global JS in WeChat development?

2.

JS dynamic modification style for WeChat development

3.

Detailed explanation of examples of referencing other js files for WeChat development

4.

Example tutorial on life cycle functions of WeChat development

The above is the detailed content of Detailed explanation of mini program development using Underscore.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn