最近开始学习Zepto源代码,分享出来,共同学习。前端新人,技术欠佳,多多见谅
参考的gitbook地址
感谢作者奉献
代码主体机构:
定义Zepto——核心自执行函数 函数里面的变量都为私有变量,防止污染全局var zepto = (function (){})(); 自执行函数
定义全局Zepto
核心函数 函数常用示例 $('div');
init函数:
zepto.init = function (selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector == 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) dom = zepto.fragment(selector, RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) dom = [selector], selector = null // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) }
如果传递的第一个参数为string——首字母为< 并且时html标签 创建新的DOM
否则如果为正常的字符串直接获取DOM
如果有第二项参数 递归调用只有单参数本方法 并且执行find方法
如果传递的参数为函数——作为ready的回调传递
如果已经时zepto对象 直接返回
如果是DOM数组
如果是单个DOM
如果是html片段
返回一个执行的函数
zepto.Z函数:
// `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. This method can be overridden in plugins. zepto.Z = function (dom, selector) { return new Z(dom, selector) }
Z函数
function Z(dom, selector) { var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) this[i] = dom[i] this.length = len this.selector = selector || '' }