Util Class
是underscore风格的工具集,提供一些常用的工具函数
Item Index
Methods
- augment static
- available static
- bind static
- buffer static
- clone static
- date static
- each static
- endsWith static
- error static
- escapeHTML
- extend static
- filter static
- globalEval static
- guid static
- inArray static
- indexOf static
- isArray static
- isBoolean static
- isDate static
- isEmptyObject static
- isFunction static
- isNumber static
- isObject static
- isPlainObject static
- isRegExp static
- isString static
- isWindow static
- keys static
- lastIndexOf static
- later static
- log static
- makeArray static
- map static
- merge static
- mix static
- namespace static
- param static
- parseXML static
- ready static
- reduce static
- startsWith static
- substitute static
- throttle static
- trim static
- unEscapeHTML static
- unique static
- unparam static
Methods
augment
-
targetClass
-
source
-
[overite=true]
-
[whitelist]
将source自身或其prototype属性的成员复制到targetClass.prototype上
Parameters:
Returns:
扩充后的类
available
-
id
-
fn
在页面id元素生效时立刻执行回调函数fn
bind
-
fn
-
context
-
[args]
创建一个新函数,该函数可以在固定的上下文以及传递部分固定参数放在用户参数前面给原函数并执行
Parameters:
Returns:
符合需求的新函数
Example:
改变运行上下文
bind 最简单的用法是生成一个新的函数,无论它如何调用,都运行在一个固定的 this 值中.入门者常犯的错误时从一个对象获得一个方法引用, 然后在后面的调用中期望这个方法的this就是原来的对象(eg.g 把这个方法用在某个回调中). 如果没有特例,那么这个原始对象就丢失了. 但是如果从原方法中得到一个绑定原始对象的函数,这个问题就解决了!
var x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = Util.bind(getX,module);
boundGetX(); // 81
Currying
bind 的下一个简单用法是产生一个具备默认参数的函数. 这些参数跟在 context 后面,无论何时调用绑定函数, 当绑定函数调用目标函数时会把它们放在参数列表开头,然后才是传递给绑定函数的用户参数
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// Create a function with a preset leading argument
var leadingZeroList = Util.bind(list,undefined, 37);
var list2 = leadingZeroList(); // [37]
var list3 = leadingZeroList(1, 2, 3); // [37, 1, 2, 3]
buffer
-
fn
-
ms=150
-
context
将fn缓存一段时间后再回调执行 Note:
- 此方法为了避免在 ms 段时间内, 执行 fn 多次. 常用于 resize , scroll , mousemove 等连续性事件中;
- 当 ms 设置为 -1, 表示立即执行 fn, 即和直接调用 fn 一样;
Parameters:
Returns:
返回缓存后的函数对象
Example:
self.__onResize = Util.buffer(doResize, 100, this);
$(window).on("resize", self.__onResize);
clone
-
o
-
[filter]
创建一个普通对象或数组的深拷贝, 并且返回
Parameters:
-
o
Object待拷贝的对象或数组
-
[filter]
Function optional过滤函数,返回false则不拷贝该元素。传入参数为:
- 待克隆值为数组, 参数同 Util.filter() , 上下文对象为全局 window
- 待克隆值为普通对象, 参数为对象的每个键对应的值, 每个键, 当前对象.(PS:上下文对象为当前对象)
Returns:
拷贝后的新对象
Example:
var a={x:{y:{z:1}}}
var b=Util.clone(a); // => b={x:y:{z:1}} , b!==a
var c=Util.clone(a,function(v,k){if(k=="z") return false;}) // => c={x:{y:{}}}
each
-
o
-
fn
-
[context=window]
遍历数组中的每一项, 执行指定方法.
Parameters:
Example:
var arr = [1, 2, 3, 4, 5],
obj = {
'hi': 'kissy',
'bye': 'world'
},
sum = 0;
Util.each(arr, function(item) {
sum += item;
});
Util.log(sum); // => 15
Util.each(obj, function(v,k) {
Util.log([v,k]);
});
error
-
msg
抛出错误异常 Note
- 只有在 debug 模式下并且载入 seed.js, 才会抛出异常. debug 模式的说明请参考 Config
Parameters:
-
msg
String异常信息
escapeHTML
-
str
将字符串经过 html 转义得到适合在页面中显示的内容, 例如替换 < 为 < Note
- 此函数只会对以下符号进行 escape:
& > <
/ " '`
Parameters:
-
str
String要显示在页面中的真实内容
Returns:
经过 html 转义后的字符串
extend
-
subClass
-
parentClass
-
[prototypeMembers]
-
[staticMembers]
让子类 SubClass 继承父类 ParentClass
Parameters:
Returns:
subClass 需要的子类函数
Example:
function Bird(name) { this.name = name; }
Bird.prototype.fly = function() { alert(this.name + ' is flying now!'); };
function Chicken(name) {
Chicken.superclass.constructor.call(this, name);
}
Util.extend(Chicken, Bird,{
fly:function(){
Chicken.superclass.fly.call(this)
alert("it's my turn");
}
});
new Chicken('kissy').fly();
filter
-
arr
-
fn
-
[context=window]
遍历数组, 过滤出符合条件的数组项
Parameters:
Returns:
返回符合过滤函数的新数组
Example:
var arr = [1, 2, 3, 4, 5];
var ret = Util.filter(arr, function(item) {
return item % 2 === 0;
});
Util.log(ret); // => [2, 4]
inArray
-
elem
-
arr
判断元素 elem 是否在数组 arr 中
Parameters:
-
elem
Any任意对象
-
arr
Array数组
Returns:
元素 elem 是否在数组 arr 中
indexOf
-
elem
-
arr
返回元素 elem 在数组 arr 中的序号
Parameters:
-
elem
Any任意对象
-
arr
Array数组
Returns:
元素 elem 在数组 arr 中的序号
isPlainObject
-
o
判断是否是普通对象, 通过 {} 或 new FunctionClass/Object() 创建的, 不包括内置对象以及宿主对象.
Parameters:
-
o
Any判断参数
Returns:
lastIndexOf
-
elem
-
arr
返回元素 elem 在数组 arr 中最后出现的序号
Parameters:
-
elem
Any任意对象
-
arr
Array数组
Returns:
later
-
fn
-
when
-
[periodic=false]
-
[o]
-
[data]
延迟执行指定函数 fn
Parameters:
Returns:
Example:
Util.later(function(data) {
S.log(data);
}, 0, false, null, 'I am later data.');
log
-
msg
-
cat="log"
-
src
输出调试信息
makeArray
-
o
将对象 o 转换为数组.
Parameters:
-
o
Objectarguments, NodeList 等 array-like 对象或单个对象
Returns:
o 转换后的数组
map
-
arr
-
fn
-
[context=window]
创建一个新数组, 数组结果是在对每个原数组元素调用指定函数的返回值.
Parameters:
Returns:
返回符合根据指定函数调用得到新数组
merge
-
s1
-
[...]
将多个对象的成员合并到一个新对象上. 参数中, 后面的对象成员会覆盖前面的.
Returns:
合并属性后的新对象
Example:
var a = { a: 'a' },
b = { b: 'b' },
c = { b: 'b2', c: 'c' };
var o = Util.merge(a, b, c);
Util.log(o.a); // => 'a'
Util.log(o.b); // => 'b2'
Util.log(o.c); // => 'c'
mix
-
receiver
-
supplier
-
[overwrite=true]
-
whitelist
-
deep
将 supplier 对象的成员复制到 receiver 对象上.
Parameters:
Returns:
receiver 属性接受者对象
Note
receiver 会被改变,如果想要保留原始的 receiver ,可以使用 Util.merge()
var object=S.merge(object1,object2);
S.mix 默认不是递归进行的. 如果其中一个属性为对象或者数组,那么他将会被接下来对象的同名属性对应的值所代替,即值不会被合并。 如果设置了参数 deep = true ,那么会对数组和简单对象( Util.isPlainObject()
)递归合并
supplier undefined 的属性值不会被复制,不过对象从原型继承下来下的值则会被复制
该方法仅适用于 javascript 对象,不要再浏览器对象上调用,例如 node.style
mix 支持函数作为白名单参数
var a = {},
b = {
b1: 1,
b2: {
b2: 22
}
};
Util.mix(a, b, {
deep: true,
whitelist: function (name, v) {
if (name == 'b1') {
return v;
}
if (this.b1 && name == 'b2') {
return v;
}
return undefined;
}
});
Example:
简单 mix:
var r = { a: 'a', b: 'b' };
Util.mix(r, { c: 'c' });
Util.log(r.c); // => 'c'
Util.mix(r, { a: 'a2' }, false);
Util.log(r.a); // => 'a'
Util.mix(r, { e: 'e', f: 'f' }, true, ['f']);
Util.log(r.e); // => undefined
Util.log(r.f); // => 'f'
深度 mix:
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
//merge object2 into object1, recursively
Util.mix(object1,object2,undefined,undefined,true);
Util.log(object1); // => { apple: 0, banana: { weight: 52, price: 200 }, cherry: 97, durian: 100 }
该方法在 KISSY 里具有非常重要的地位. JavaScript 是一门动态语言, 利用 mixin 特性, 可以很方便的实现特性的静态复制和动态修改.
param
-
o
-
[seq="&"]
-
[eq="]
-
[arr=true]
将对象 o 转换为参数字符串, 用于发送 http 请求
Parameters:
Example:
Util.param({ foo: 1, bar: 2 }); // => foo=1&bar=2
Util.param({ foo: 1, bar: [2, 3] }); // => foo=1&bar%5B%5D=2&bar%5B%5D=3
Util.param({ foo: 1, bar: [2, 3] },'&','=',false); // => foo=1&bar=2&bar=3
Util.param({ foo: '', bar: 2 }); // => foo=&bar=2
Util.param({ foo: undefined, bar: 2 }); // => foo&bar=2
parseXML
-
str
将字符串转化为 xml 文档
Parameters:
-
str
String有效的 xml 文档字符串 return {XML} xml 文档
Example:
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>";
var xmlDoc=Node.all(Util.parseXML(xml));
alert(xmlDoc.one("title").text()); // => RSS Title
reduce
-
arr
-
fn
-
initialValue
从左向右对每个数组元素调用给定函数,并把返回值累积起来
Parameters:
Returns:
累计值
Note
reduce 对数组中的每个元素执行 fn 函数,该 fn 接受四个参数:initialValue (或者上次调用 fn 的返回值), 数组的当前元素,数组的当前位置以及用于遍历的数组.
调用 reduce 类似于:Util.reduce([],function(previousValue, currentValue, index, array));
当第一次调用 fn 时 :
- 如果调用 reduce 时没有设定 initialValue,previousValue 和 currentValue 是数组的前两个值.
- 如果调用 reduce 时设定了 initialValue,那么 previousValue 和 initialValue 相等 ,而 currentValue 则和数组的第一个元素相等.
Example:
Util.reduce([0,1,2,3,4],function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
// First call
previousValue = 0, currentValue = 1, index = 1
// Second call
previousValue = 1, currentValue = 2, index = 2
// Third call
previousValue = 3, currentValue = 3, index = 3
// Fourth call
previousValue = 6, currentValue = 4, index = 4
// array is always the object [0,1,2,3,4] upon which reduce was called
// Return Value: 10
Util.reduce([0,1,2,3,4],function(previousValue, currentValue, index, array){
return previousValue + currentValue;
}, 10);
// First call
previousValue = 10, currentValue = 0, index = 0
// Second call
previousValue = 10, currentValue = 1, index = 1
// Third call
previousValue = 11, currentValue = 2, index = 2
// Fourth call
previousValue = 13, currentValue = 3, index = 3
// Fifth call
previousValue = 16, currentValue = 4, index = 4
// array is always the object [0,1,2,3,4] upon which reduce was called
// Return Value: 20
得到数组的值总和
var total = Util.reduce([0, 1, 2, 3],function(a, b){ return a + b; }); // total == 6
嵌套数组平坦化
var flattened = Util.reduce([[0,1], [2,3], [4,5]],function(a,b) {
return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
substitute
-
str
-
o
将字符串中的占位符替换为对应的键值
Returns:
将模板和数据结合起来的最终字符串
Example:
var str = '{name} is {prop_1} and {prop_2}.',
obj = {name: 'Jack Bauer', prop_1: 'our lord', prop_2: 'savior'};
Util.substitute(str, obj); // => 'Jack Bauer is our lord and savior.'
throttle
-
fn
-
ms
-
context
ms 时间内只执行 fn 一次, 即使这段时间内 fn 被调用多次.
Parameters:
Returns:
返回缓存后的函数对象 Note
- 当 ms 设置为 -1, 表示立即执行 fn, 即和直接调用 fn 一样;
- throttle 和 buffer 的区别在于, 前者表示间隔内的函数触发被忽略, 后者表示间隔内的触发被放到下个间隔触发
Example:
function sayHi() {
alert('hi');
}
say = Util.throttle(sayHi, 300, this);
say(); // 忽略
Util.later(say, 200); // 忽略
Util.later(say, 350); // 超过300ms后, 终于执行
unEscapeHTML
-
str
将字符串中的 html 实体字符替换成对应字符
Parameters:
-
str
String包含 html 实体字符的字符串
Returns:
替换实体字符后的字符串
Example:
Util.unEscapeHTML("<a>x</a>"); // => "<a>x</a>"
Note
该函数只会 unescape 以下字符序列(正则式
& < > ` / " ' &#\d{1,5}
unparam
-
str
-
[seq="&"]
-
[eq="]
将参数字符串 str 还原为对象
Parameters:
Returns:
参数的对象表示
Example:
Util.unparam('foo=1&bar=2'); // => { foo: 1, bar: 2 }
Util.unparam('foo=%81%47'); // gbk 编码 => { foo: "%81%47" } 而不是 {foo: "丢"}
Util.unparam('foo=1&bar=2&bar=3'); // => { foo: 1, bar: [2, 3] }
Util.unparam('foo=1&bar%5B%5D=2&bar%5B%5D=3'); // => { foo: 1, bar: [2, 3] }