最近兼職的項(xiàng)目里面因?yàn)橐胏harts進(jìn)行數(shù)據(jù)的交互式可視化,用Chart.js比較多,也踩了不少坑。
為了改bug提pr外加學(xué)習(xí)一下提高姿勢水平花了一點(diǎn)時(shí)間看了下源碼,發(fā)現(xiàn)一些比較有用簡介的helper function很值得學(xué)習(xí)及日常使用。
代碼
var helpers = {};
// -- Basic js utility methods
helpers.each = function(loopable, callback, self, reverse) {
// Check to see if null or undefined firstly.
var i, len;
if (helpers.isArray(loopable)) {
len = loopable.length;
if (reverse) {
for (i = len - 1; i >= 0; i--) {
callback.call(self, loopable[i], i);
}
} else {
for (i = 0; i < len; i++) {
callback.call(self, loopable[i], i);
}
}
} else if (typeof loopable === 'object') {
var keys = Object.keys(loopable);
len = keys.length;
for (i = 0; i < len; i++) {
callback.call(self, loopable[keys[i]], keys[i]);
}
}
};
helpers.clone = function(obj) {
var objClone = {};
helpers.each(obj, function(value, key) {
if (helpers.isArray(value)) {
objClone[key] = value.slice(0);
} else if (typeof value === 'object' && value !== null) {
objClone[key] = helpers.clone(value);
} else {
objClone[key] = value;
}
});
return objClone;
};
helpers.extend = function(base) {
var setFn = function(value, key) {
base[key] = value;
};
for (var i = 1, ilen = arguments.length; i < ilen; i++) {
helpers.each(arguments[i], setFn);
}
return base;
};
使用場景
helpers.each
提供了數(shù)組和Object統(tǒng)一的遍歷函數(shù),實(shí)際使用舉例:
helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) {
xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
});
helpers.clone
提供了完整的深拷貝函數(shù),與常用的JSON.parse(JSON.stringify(obj))的區(qū)別在于這個(gè)函數(shù)可以深拷貝對象內(nèi)的函數(shù)。
Chart.js內(nèi)部用這個(gè)進(jìn)行config之類的merge時(shí),先深拷貝然后再擴(kuò)展,比較方便。
var base = helpers.clone(_base);
helpers.extend
Chart.js的設(shè)計(jì)思想包含了很多plugin形式,本身的Chart的核心功能也都有擴(kuò)展的方式定義的,關(guān)鍵就在extend。
helpers.extend(Chart.prototype, /** @lends Chart */ {
/**
* @private
*/
construct: function(item, config) {
// ...
},
/**
* @private
*/
initialize: function() {
// ...
},
// ...
}
可以看出直接給原型進(jìn)行擴(kuò)展,寫起來非常簡潔。