In recent part-time projects, because of the interactive visualization of data with charts, there are more charts. js, but also a lot of pits.
In order to change the bug, pr and learn how to improve the posture level, I spent a little time looking at the lower source code and found some useful introductions. helper function It is worth learning and daily use.
Code
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; };
Usage scenarios
helpers.each
A unified traversal function for arrays and objects is provided. Examples are given for practical use.
helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) { xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index); });
helpers.clone
A complete deep copy function is provided, which differs from the commonly used JSON.parse(JSON.stringify(obj)) in that it can deeply copy functions within objects.
When Chart.js uses this to config or other merge s, it's more convenient to copy them deeply and then expand them.
var base = helpers.clone(_base);
helpers.extend
Chart.js's design idea includes many plugin forms, and its core functions are also defined in an extend ed way. The key is extension.
helpers.extend(Chart.prototype, /** @lends Chart */ { /** * @private */ construct: function(item, config) { // ... }, /** * @private */ initialize: function() { // ... }, // ... }
It can be seen that the prototype can be extended directly and written very concisely.