@molay/common

0.1.0-alpha-2 • Public • Published

JavaScript Common Library

JavaScript 通用库

event

EventDispatcher 事件派发器

EventDispatcher 实现标准的观察者模式,可用于任意需事件监听的场合。

继承使用:

import {EventDispatcher} from '@molay/common';
class ClassA extends EventDispatcher {
}

const a = new ClassA();
// 添加类型为 event1 的事件监听
a.on('event1', function (e) { console.log(e); });
// 派发类型为 event1 的事件
a.fire({ type: 'event1' });
// 从对象 a 上删除所有类型为 event1 的事件监听,如果不传类型参数将删除 a 上所有事件监听
a.off('event1');
// 此时再派发类型为 event1 的事件将不会有任何操作被执行
a.fire({ type: 'event1' });

混合使用:

import {EventDispatcher} from '@molay/common';
class ClassA extends OtherBaseClass {
}

const a = new ClassA();
// 为对象 a 创建 EventDispatcher 方法,
// 前提 a 上不能有任何与 EventDispatcher 同名的方法存在
EventDispatcher.createInterface(a);
// 使用方式与继承使用相同
a.on('event1', function (e) { console.log(e); });
a.fire({ type: 'event1' });

/*
 * EventDispatcher.createInterface(target, force, abbr)
 * - target 待包装为 EventDispatcher 的对象,包装后即可使用 EventDispatcher 方法
 * - force 是否强制包装,即无视 target 上是否已存在与 EventDispatcher 同名的方法,默认为 false
 * - abbr 是否是用语法糖缩写(on、off、fire),默认为 true
 */

math

Constant 常数

  • UA (Unit Angle): pi / 180
  • AU (1 / Unit Angle): 180 / pi
  • PI (Pie): pi
  • DP (Double Pie): pi * 2
  • HP (Half of Pie): pi / 2
  • QP (Quarter of Pie): pi / 4

util

RandomUtil 随机方法集

RandomUtil 提供常用的随机工具方法。

import {randomId} from '@molay/common';

// 生成随机的Id。
console.log(randomId());

ImageCache 图形缓存

ImageCache 用于统一管理图形资源。

import {ImageCache} from '@molay/common';

const imageCache = new ImageCache();
const image0 = imageCache.get('/path/to/image');
if (image0.complete) {
  // do sth.
}
else {
  image0.on('loaded', function () {
    // do sth.
  });
}

Timer 定时器

Timer 继承自 EventDispatcher ,可用于任意需定时调用的场合。

import {Timer} from '@molay/common';

// 每秒执行一次,永不停止。
const timer0 = new Timer(1000);
timer0.on('timer', function () { console.log(1); });
timer0.start();

// 以屏幕刷新率执行,永不停止。
const timer1 = new Timer(Timer.REQUEST_ANIMATION_FRAME);
timer1.on('timer', function () { console.log(1); });
timer1.start();

// 每秒执行一次,执行10次便停止,在停止后,若不重置定时器,则启动会立刻停止。
const timer2 = new Timer(1000, 10);
timer2.on('timer', function () { console.log(timer2.currentCount); });
timer2.on('timerComplete', function () { console.log('time is completed!'); });
timer2.start();

// 停止、重置、取消事件。
timer2.stop();
timer2.reset();
timer2.off('timer');

Readme

Keywords

Package Sidebar

Install

npm i @molay/common

Weekly Downloads

1

Version

0.1.0-alpha-2

License

CC-BY-NC-ND-4.0

Unpacked Size

33.9 kB

Total Files

6

Last publish

Collaborators

  • molay