-
Notifications
You must be signed in to change notification settings - Fork 12
API Docs
ukyo edited this page Dec 25, 2012
·
2 revisions
ユーティリティ関数群
jz.utils.Deferred
はjQueryライクなDeferredを提供します。
一定時間待つ関数:
function wait(ms) {
// Deferredのインスタンスを生成
var deferred = new jz.utils.Deferred;
setTimeout(function() {
console.log(Date.now());
// 処理完了時にresolveを呼ぶ
deferred.resolve(ms);
}, ms);
// 必ずpromiseを返すこと
return deferred.promise();
}
wait(1000).then(onResolved, onRejected);
function onResolved(arg) {
console.log(arg);
}
function onRejected(err) {
console.log(err.message);
}
then
は連鎖的に書くことができます:
wait(1000)
.then(wait);
.then(wait);
.then(wait);
then
のエイリアスとしてdone
とfail
というメソッドがあります:
// 以下の2つは同義
wait(1000).done(callback);
wait(1000).then(callback, null);
// 以下の2つは同義
wait(1000).fail(callback);
wait(1000).then(null, callback);
then
の引数に渡された関数のthis
コンテキストは共有されます:
wait(1000)
.then(function() {
this.foo = 'foo';
})
.then(function() {
console.log(this.foo === 'foo');
});
then
の引数に渡された関数がエラーを投げたら直近のonRejectedが呼ばれます:
wait(1000)
.then(function() {
throw new Error('error!!!');
})
.then(function() {
'should not be called.';
})
.fail(function(e) {
console.log(e.message);
});
見た目並列に実行します:
// 約3000ミリ秒後にonResolvedが呼ばれます
jz.utils.parallel(wait(1000), wait(2000), wait(3000))
.done(function(a, b, c) {
console.log(a, b, c); // 1000, 2000, 3000
});
色々なバイト表現をUint8Array
にして返す。
jz.utils.toBytes([0x60, 0x61, 0x62]);
jz.utils.toBytes('\x60\x61\x62');
jz.utils.toBytes(new ArrayBuffer(3));
jz.utils.toBytes(new Uint8Array([0x60, 0x61, 0x62]));
複数のファイルをXMLHttpRequest
を用いてArrayBuffer
として読み込む。
jz.utils.load('foo.txt', 'bar.txt')
.done(function(foo, bar) {
// ...
})
バイト表現を文字列に変換する。
// デフォルトの文字コードはUTF-8
jz.utils.bytesToString(bytes)
.done(function(text) {
console.log(text);
});
// 第2引数にエンコーディングを指定することができる
jz.utils.bytesToString(bytes, 'Shift_JIS')
.done(function(text) {
console.log(text);
});
バイト表現のadler32チェックサムを得る
jz.algorithms.adler32(bytes);
バイト表現のadler32チェックサムを得る
jz.algorithms.crc32(bytes);
jz.algorithms.deflate(bytes[, level]);
jz.algorithms.inflate(bytes);
jz.zlib.compress(bytes[, level]);
jz.zlib.decompress(bytes);
jz.gz.compress(bytes[, level]);
jz.gz.decompress(bytes);
jz.zip.pack(files[, level]).then(function(buffer) {
// ...
}, function(e) {
// ...
});
var files = [
{name: 'foo.txt', str: 'foo'},
{name: 'bar.mp3', url: 'path/to/bar.mp3'},
{name: 'baz.txt', buffer: buff},
{name: 'dir1', dir: [
{name: 'dir2', folder: [
{name: 'dir3', children: [
{name: 'a.txt', str: 'a'}
]}
]}
]}
];
jz.zip.pack(files, 9)
.done(function(buffer) {
// ...
});
var files = [
{name: 'foo.txt', str: 'foo', level: 9},
{name: 'bar.mp3', url: 'path/to/bar.mp3'},
{name: 'baz.txt', buffer: buff},
{name: 'dir1', dir: [
{name: 'dir2', folder: [
{name: 'dir3', children: [
{name: 'a.txt', str: 'a'}
]}
]}
]}
];