1.0.5 β€’ Published 2 years ago

fecmjs v1.0.5

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

fecmjs

English | δΈ­ζ–‡

Features

  1. Collection of common front-end methods to facilitate normal development

  2. Applicable to mobile terminal, PC terminal, mobile terminal first (some methods come from the Internet)

  3. Modular development for easy reference

  4. Support tree shaking to reduce packing volume

Introduce

This tool is currently divided into four modules 1. Form: It contains general form validation methods, character judgment of user input information, etc. 2. Common: It contains some methods that are often used in mobile terminal development 3. Info: It contains some information about the current mobile device 4. Ajax: It contains the encapsulated ajax request method

Usage

  • use the npm method
npm i fecmjs
// 1. Use all modules
import * as Fecmjs from 'fecmjs';
const {Form, Normal, Info} = Fecmjs;
const flag = Form.checkEmail('limingcan562@163.com');
console.log(flag); // true
// 2. When you only need to use some functions, you can import some modules (recommended)
import {Form, Normal, Info} from 'fecmjs';
const flag = Form.checkEmail('limingcan562@163.com');
console.log(flag); // true
  • Use <script></script> to import
<script src="https://cdn.xxxx/fecmjs.min.js"></script>
<script>
    var Form = Fecmjs.Form;
    var flag = Form.checkEmail('limingcan562@163.com');
    console.log(flag); // true
</script>

Common module

loadImage(src) load images

parameter namedescriptiondefault value
srcURL of the image to load''

Example:

Common
.loadImage('http://xxxx')
// loaded successfully
.then(img => {
    
})
// Failed to load
.catch(err => {
    
});

wait(delay) delay

parameter namedescriptiondefault value
delaydelay time500

Example:

Common
.wait(1000)
// Execute after a delay of 1s
.then( => {
    
});

showTips({}) Show tips popup

parameter namedescriptiondefault value
autoCloseWhether to close automaticallytrue
delayhow many seconds after which to automatically close1000
textprompt textloading...
closedFnclosed callback() => {}

Example:

Common
.showTips({
    autoClose: false,
    delay: 2000,
    text: 'please waiting',
    closedFn: () => {
        console.log('closed');
    }
});

closeTips() close the prompt popup

Description: Applicable when autoClose: false of showTips

Example:

Common.closeTips();

isVisibleArea(domEle) Whether the element appears in the viewport

parameter namedescriptiondefault value
domEledom element{}

Example:

const dom = document.getElementById('ele');
const isShow = Common.isVisibleArea(dom);
// element is in viewport
if (isShow) {

}
// element is not in viewport
else {

}

Form module

checkID(ID) Verify ID

parameter namedescriptiondefault value
IDID card (only supports mainland ID cards)''

Example:

const flag = Form.checkID('441522xxxxxxxxxxxx');
// ID card format is correct
if (flag) {

}
// wrong ID format
else {

}

checkEmail(email) Verify email

parameter namedescriptiondefault value
emailmailbox''

Example:

const flag = Form.checkEmail('xxxx@gmail.com');
// Email format is correct
if (flag) {

}
// Email format error
else {

}

isPhoneNum(phone) Verify phone number

parameter namedescriptiondefault value
phonemobile phone number (only supports mainland mobile phones)''

Example:

const flag = Form.isPhoneNum('1581xxxxx81');
// phone number format is correct
if (flag) {

}
// Wrong format of phone number
else {

}

rangeRandom(min, max) generate range random integers

parameter namedescriptiondefault value
minminimum value to generate0
maxmaximum value to generate0

Example:

// will generate random numbers from 1 to 10
const num = Form.isPhoneNum(1, 10);

removeEmoji(content) remove the emoji from the string

parameter namedescriptiondefault value
contentString content

Example:

const str = Form.removeEmoji('hello,I am 🍁');
console.log(str); // hello,I am

allChinese(val) Determine whether it is pure Chinese (excluding spaces, special characters)

parameter namedescriptiondefault value
valstring content''

Example:

const str = Form.allChinese('How are you?');
console.log(str); // false because there is a special character question mark

allEnglish(val) to determine whether it is pure English (excluding spaces, special characters)

parameter namedescriptiondefault value
valstring content''

Example:

const str = Form.allEnglish('hello world');
console.log(str); // false because of spaces

hasSpecialCharacters(str) to determine whether there are special characters

parameter namedescriptiondefault value
strstring content''

Example:

const str = Form.allEnglish('??!');
console.log(str); // true

removeSpaceSrt(str) remove spaces from the string

parameter namedescriptiondefault value
strstring content''

Example:

const str = Form.allEnglish('hello, I am lMC');
console.log(str); // hello, IamlMC

Info module

attribute namedescriptionvalue description
platformis the mobile terminal or the pc terminal.pc: pc sidemobile: mobile side
screenTypemobile phone screen typeX: full screen normal: normal screen (iphone5, 6, 7) short: smaller screen than normal screen
sysTemdevice systemios: ios system android: android Android system not moblie: current non-mobile terminal
isWechatIs the current WeChat environmenttrue: the current WeChat environment false: the current non-WeChat environment

Ajax module

Ajax module exports a class

Equivalent to a global configuration

parameter namedescriptiondefault value
config.typerequest typePOST
config.debugWhether to enable interface printing information (recommended to be disabled in production environment)0
config.debugStepWhether to enable printing of the four steps of xhr connection for debugging0
config.headersSet request headers. GET request, the value is: application/x-www-form-urlencoded; charset=UTF-8;POST request, the value is: application/x-www-form-urlencoded; charset=UTF-8;When passed When data is of type FormData, the setting will be invalid{}
config.urlrequest URL''
config.datarequest parameters{}
config.timeoutinterface timeout3000
config.successStatus code 200 Successful callback, res is the result returned by the interfaceres => {}
config.failThe status code is not 200 The failure callback, res is the result returned by the interfaceres => {}
config.alwaysA callback triggered on success or failure, res is the result returned by the interfaceres => {}
config.timeoutFnInterface timeout callback, res native event callback objectres => {}
config.errorinterface error callback, res native event callback objectres => {}
config.fieldNameThe field representing the status code returned by the backendret
config.successCodeThe success status value returned by the backendsuccess
config.responseDataNamebackend data field namedata

Example:

import {Ajax} from 'fecmjs';
const ajax = new Ajax({
    debug: 0,
    url: 'xxxxx',
    timeout: 2000
});
ajax.base({
    success: res => {
        console.log('ηŠΆζ€η 200 成功');
        if (ret.ret === 0) {
            // do someting
        } else {
            // fail
        }
    },
    fail: res => {
        console.log('ηŠΆζ€η ιž200 ε€±θ΄₯');
    }
});

base(config) request method

Enter some of the parameters that can be passed in to the default global parameters. If they are passed in again, the default global parameters will be overwritten.

Example:

ajax.base({
    type: 'get',
    debug: 0,
    url: 'xxxxx',
    timeout: 2000,
    success: res => {
        console.log('status code 200 success');
        if (ret.ret === 0) {
            // do something
        } else {
            // fail
        }
    },
    fail: res => {
        console.log('Failure with status code other than 200');
    }
});

rebuild(config) wraps the base method

  • This method is encapsulated once again with the base method according to the data format returned by the backend. So when you want to use it, you need to configure fieldName, successCode, failCode and responseDataName in the new Ajax() method
  • When the status code is 200 and the success status returned by the backend is satisfied, then the function is successful and returns a Promise. The parameters in the then function are the data returned by the backend
  • When the status code is 200, and the non-successful status returned by the backend is satisfied, or it is triggered when the interface is called, timeFn, error will trigger the catch function
  • The input parameter config only accepts the following parameters
    • data
    • url
    • type
    • headers
    • timeout
    • debug
    • debugStep

When entering the catch function, you can judge the type of the current error according to the err parameter of the catch function

Possible values for the catch function err._type (parameter): possible values | value description ---- | ---- connect error | connection error connect timeout | connection timeout connect fail | connection fail interface fail | The connection is successful, the interface returns a non-success status code other errors| Other errors, possibly due to your own code writing errors

Example:

// 1. Suppose the data returned by the backend successfully is in the format:
/**
 * @ret is config.fieldName
 * @success is config.successCode
 * @data is config.responseDataName
 */
{
    ret: 'success',
    data: {
        name: 'lmc',
        age: 27
    }
}

// 2. Initialize configuration
const ajax = new Ajax({
    fieldName: 'ret',
    successCode: 'success',
    responseDataName: 'data'
});

// 3. call
ajax.rebuild({
    type: 'get',
    debug: 0,
    url: 'xxxxx',
    timeout: 2000,
})
// interface succeeded
.then(res => {
    // res ==> data: {name: 'lmc', age: 27}
})
// If ret !== 'success', fail (including timeFn, error, will trigger catch)
.catch(err => {
    // connect error
    if (err._type === 'connect error') {

    }
    // connect timeout
    else if (err._type === 'connect timeout') {

    }
    // interface fail
    else if (err._type === 'interface fail') {
        
    }
    // other errors
    else if (err._type === 'other errors') {
        
    }
})

other

In dis/ajax.min.js, there are Ajax modules extracted separately, which can also be directly used

import Ajax from 'fecmjs/plugin/ajax.esm';

const ajax = new Ajax({
    debug: 0,
    url: 'xxxxx',
    timeout: 2000
});


ajax.base({
    type: 'get',
    url: 'xxxx',
    data: {
        type: 5,
    },
    timeout: 1000,
    success: res => {
        console.log('succss', res);
    },
    fail: res => {
        console.log('fail', res);
    }
});
<script src="./ajax.min.js"></script>
<script>
    const ajax = new Ajax({
        debug: 0,
        url: 'xxxxx',
        timeout: 2000
    });


    ajax.rebuild({
        type: 'get',
        url: 'xxxx',
        data: {
            type: 5,
        },
        timeout: 1000,
    })
    .then(res => {
        console.log('succss', res);
    })
    .catch(res => {
        console.log('fail', res);
    });
</script>
1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago