zepto源代码解读
/**
* Created by nono on 14-11-16.
*/
/* Zepto v1.1.4 - zepto event ajax form ie - zeptojs.com/license */
var Zepto = $ = {};
$.fn = {};
var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter,
document = window.document,
elementDisplay = {},
classCache = {},
cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
// /^\s* 空格或者没有空格 <(\w+|!)标签内有内容[^>非结束标签]*> 标签结束/ 匹配内部的所有内容;
fragmentRE = /^\s*<(\w+|!)[^>]*>/,
// /^<(\w+) 标签名字 \s*\ 有或者没有空格/?>有结束或者没有结束标签(?:<\/\1>|) 断言的结束标签,可以有或在可以没有$/;
singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig;
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
//匹配某个字符是否就是"html"或者"body";
rootNodeRE = /^(?:body|html)$/i,
//有一个大写字母的话;
capitalRE = /([A-Z])/g, //设置属性的会掉用方法
// special attributes that should be get/set via method calls;
methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
table = document.createElement('table'),
tableRow = document.createElement('tr'),
containers = {
//tr的父级为tbody;
'tr': document.createElement('tbody'),
//tbody,thead,tfoot的父级为table;
'tbody': table,
'thead': table,
'tfoot': table,
//同上;
'td': tableRow,
'th': tableRow,
'*': document.createElement('div')
},
//onreadystatechange 事件中的 readyState 是否加载完成的
readyRE = /complete|loaded|interactive/,
//这个正则会匹配所有的字符串和-
simpleSelectorRE = /^[\w-]*$/,
//
class2type = {},
//快捷方法, 做类型判断;
toString = class2type.toString,
//小写的zepto, 对象
zepto = {},
//camelize, underscore, dashlize, capitalize;
camelize, uniq,
tempParent = document.createElement('div'),
//保留字腰转换
propMap = {
'tabindex': 'tabIndex',
'readonly': 'readOnly',
'for': 'htmlFor',
'class': 'className',
'maxlength': 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
'rowspan': 'rowSpan',
'colspan': 'colSpan',
/*
<img src="planets.gif" alt="Planets" usemap="#planetmap" /> <map name="planetmap">
<area href="sun.htm" shape="rect" coords="0,0,110,260">Sun</a>
<area href="mercur.htm" shape="circle" coords="129,161,10">Mercury</a>
<area href="venus.htm" shape="circle" coords="180,139,14">Venus</a>
</map>
*/
'usemap': 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},
//简单的判断;
isArray = Array.isArray ||
function(object){ return object instanceof Array } zepto.matches = function(element, selector) {
if (!selector || !element || element.nodeType !== 1) return false
var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
element.oMatchesSelector || element.matchesSelector
//if (matchesSelector) return element.matchesSelector(selector) 是不行的;还是用call靠谱;
if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector:
var match, parent = element.parentNode, temp = !parent
//tempParent = document.createElement('div') 因为这个元素可能为加入到 html中, 只在内存中(fragment);
if (temp) (parent = tempParent).appendChild(element)
//调用querySelectorAll
//~“10" ==>> -11 ; ~"12"==>> -13;
//~~"10" ==>> 10 ; ~~23 ==>> 23;
match = ~zepto.qsa(parent, selector).indexOf(element)
//除了 值为 -1计算出的值是0; 剩下的全部是非0的;
temp && tempParent.removeChild(element)
return match
} function type(obj) {
// 非全等于null就两种东西 null他自己和 undefined
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
} function isFunction(value) { return type(value) == "function" }
function isWindow(obj) { return obj != null && obj == obj.window }
// document.DOCUMENT_NODE === 9
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
function isObject(obj) { return type(obj) == "object" }
function isPlainObject(obj) {
//是object 非window, 他的原型就是他自己;
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
//简单的直接判断length就好了;
function likeArray(obj) { return typeof obj.length == 'number' } //压缩, 把所有的 undefined 和 null去掉;
function compact(array) { return filter.call(array, function(item){ return item != null }) } //把array
//[].concat.apply([],[1,2,3,4,[6,7]]) ==>> [1, 2, 3, 4, 6, 7]
function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
function dasherize(str) {
return str.replace(/::/g, '/') //这个不是很懂为什么这样弄;
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') //"abcDef" ==> "abc_Def"
.replace(/([a-z\d])([A-Z])/g, '$1_$2') //"abc1Def" ==> "abc1_Def"
.replace(/_/g, '-') //把下划线替换成"-"
.toLowerCase() //全部变小写字符;
}
//取数值的唯一
uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
/*如果是我的话,我就会这样写
function uniq(array) {
var result = [];
for(var i=0; i< array.length; i++) {
if([].prototype.indexOf.call(array, array[i]) === i) {
result.push( array[i] );
}
};
return result;
};
*/
//返回匹配class的正则; new RegExp("^|\\s"+ youClass +"\\s|$","g")
function classRE(name) {
return name in classCache ?
classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
} //目前都是在初始化变量;
function maybeAddPx(name, value) {
return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
} //把默认的显示保存到缓存里面
function defaultDisplay(nodeName) {
var element, display
if (!elementDisplay[nodeName]) {
element = document.createElement(nodeName)
document.body.appendChild(element)
display = getComputedStyle(element, '').getPropertyValue("display")
element.parentNode.removeChild(element)
display == "none" && (display = "block")
elementDisplay[nodeName] = display
}
return elementDisplay[nodeName]
} //把Nodes转化成数组;
function children(element) {
return 'children' in element ?
slice.call(element.children) :
$.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
} // `$.zepto.fragment` takes a html string and an optional tag name
// to generate DOM nodes nodes from the given html string.
// The generated DOM nodes are returned as an array.
// This function can be overriden in plugins for example to make
// it compatible with browsers that don't support the DOM fully.
zepto.fragment = function(html, name, properties) {
var dom, nodes, container //只是单标签的情况下,优化单标签,剩下的全部跑下面代码;
// A special case optimization for a single tag
//singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) //dom为空的话说明没匹配到;
if (!dom) {
//有replace方法就说明是字符串,把原来的字符串替换成合法的html字符串;
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
//fragmentRE = /^\s*<(\w+|!)[^>]*>/,
//name必须严格等于undefined,如果name为空就永远是div为父级的;
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
//自动为元素添加父级,没有就是新建div了;
//
if (!(name in containers)) name = '*'
/*
containers = {
//tr的父级为tbody;
'tr': document.createElement('tbody'),
//tbody,thead,tfoot的父级为table;
'tbody': table,
'thead': table,
'tfoot': table,
//同上;
'td': tableRow,
'th': tableRow,
'*': document.createElement('div')
},
*/
//containers[name] = document.createElement("div")
container = containers[name]
container.innerHTML = '' + html
//把container内部的所有子元素删除, 然后返回被删除的元素;
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
});
}; //为dom这个节点添加属性;
if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {
//存在这个快捷方法的话;
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}; //dom是数组排列的DOM元素;
return dom
} // `$.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. Note that `__proto__` is not supported on Internet
// Explorer. This method can be overriden in plugins.
//把dom元素选中以后,用zepto.Z包装, 然后返回;
zepto.Z = function(dom, selector) {
dom = dom || []
//绑定原型 __proto__;
dom.__proto__ = $.fn
dom.selector = selector || ''
return dom;
} // `$.zepto.isZ` should return `true` if the given object is a Zepto
// collection. This method can be overriden in plugins.
zepto.isZ = function(object) {
//zepto.Z.prototype === $.fn ==>> true;
//zepto.Z的原型就是$.fn, $.fn必定了很多方法;
return object instanceof zepto.Z //初始化的时候手动设置zepto.Z.prototype = $.fn;
//和下面这写法一摸一样;
//var temp = function() {};
//temp.prototype = $.fn;
//return object instanceof temp;
} // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
// takes a CSS selector and an optional context (and handles various
// special cases).
// This method can be overriden in plugins.
zepto.init = function(selector, context) {
var dom
// If nothing given, return an empty Zepto collection
if (!selector) return zepto.Z()
// Optimize for string selectors
//如果是字符串就只有两种情况1:新建元素,2:查找元素;
//查找元素如果有context就按照context找,否则就从document找;
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 <
//fragmentRE = /^\s*<(\w+|!)[^>]*>/,正则匹配单标签;
if (selector[0] == '<' && fragmentRE.test(selector))
//新建dom元素;
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
//直接查找元素;
//dom = zepto.qsa(context || document, select)
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
//DOMContentready;
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 {
//$([1,2,3,4,5,5,5,6,2,2,undefined,null]) ==>> [1, 2, 3, 4, 5, 5, 5, 6, 2, 2]去除值为undefined和null的元素;
// normalize array if an array of nodes is given
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
//直接假设是dom节点元素了;
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
//试过了使用正则test这个碎片对象不行,我不知道为什么跑这边来了;
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)
} // `$` will be the base `Zepto` object. When calling this
// function just call `$.zepto.init, which makes the implementation
// details of selecting nodes and creating Zepto collections
// patchable in plugins.
$ = function(selector, context){
return zepto.init(selector, context);
} function extend(target, source, deep) {
for (key in source)
//深度复制,可能是存对象或者是数组, 是function或者是字符串或者是数字或者基本类型的不会走这边;
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
//是对象,而且target的这个属性是空的,说明不会覆盖原来的属性;
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
//新建
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = [] extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}; // Copy all but undefined properties from one or more
// objects to the `target` object.
//$.extend(a,b,c,d,e,f,g);所有的都继承到a里面去;
//深度赋值继承,$.extend(true,a,b,c,d,e,f,g);所有的都继承到a里面去;
$.extend = function(target){
var deep, args = slice.call(arguments, 1)
if (typeof target == 'boolean') {
deep = target
target = args.shift()
}
args.forEach(function(arg){ extend(target, arg, deep) })
return target
}; // `$.zepto.qsa` is Zepto's CSS selector implementation which
// uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
// This method can be overriden in plugins.
zepto.qsa = function(element, selector){
var found,
maybeID = selector[0] == '#',
maybeClass = !maybeID && selector[0] == '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
//simpleSelectorRE = /^[\w-]*$/
isSimple = simpleSelectorRE.test(nameOnly); return (isDocument(element) && isSimple && maybeID) ?
//ID
( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
(element.nodeType !== 1 && element.nodeType !== 9) ? [] :
//优化;
//转化成数组;
slice.call(
isSimple && !maybeID ?
maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
element.getElementsByTagName(selector) : // Or a tag
element.querySelectorAll(selector) // Or it's not simple, and we need to query all
)
}; //这个东西有点象match方法;
//从nodes里面选择匹配selector的元素;
function filtered(nodes, selector) {
return selector == null ? $(nodes) : $(nodes).filter(selector)
} $.contains = document.documentElement.contains ?
function(parent, node) {
return parent !== node && parent.contains(node)
} :
function(parent, node) {
while (node && (node = node.parentNode))
if (node === parent) return true
return false
}; //跑func,并用context作为上下文;
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
} //删除或者是设置;
function setAttribute(node, name, value) {
value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
} //返回className并做了svg的兼容,TMD的SVG是什么东西;
// access className property while respecting SVGAnimatedString
function className(node, value){
var klass = node.className,
svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass
svg ? (klass.baseVal = value) : (node.className = value)
} // "true" => true
// "false" => false
// "null" => null
// "42" => 42
// "42.5" => 42.5
// "08" => "08"
// JSON => parse if valid
// String => self;
//反序列化;
function deserializeValue(value) {
var num
try {
return value ?
value == "true" || ( value == "false" ? false :
value == "null" ? null :
!/^0/.test(value) && !isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value )
: value
} catch(e) {
return value
}
}; $.type = type
$.isFunction = isFunction
$.isWindow = isWindow
$.isArray = isArray
$.isPlainObject = isPlainObject $.isEmptyObject = function(obj) {
var name
for (name in obj) return false
return true
}; $.inArray = function(elem, array, i){
return emptyArray.indexOf.call(array, elem, i)
}; $.camelCase = camelize
$.trim = function(str) {
return str == null ? "" : String.prototype.trim.call(str)
} // plugin compatibility
$.uuid = 0
$.support = { }
$.expr = { } // xx != null ==>> xx!==undefined, xx!==null
//map循环的参数第一个是值,如果是array类型第二个是index,是object类型就是key;
$.map = function(elements, callback){
var value, values = [], i, key
if (likeArray(elements))
for (i = 0; i < elements.length; i++) {
value = callback(elements[i], i)
if (value != null) values.push(value)
}
else
for (key in elements) {
value = callback(elements[key], key)
if (value != null) values.push(value)
}
return flatten(values)
} $.each = function(elements, callback){
var i, key
if (likeArray(elements)) {
for (i = 0; i < elements.length; i++)
//index, value;
if (callback.call(elements[i], i, elements[i]) === false) return elements
} else {
for (key in elements)
//index, value;
if (callback.call(elements[key], key, elements[key]) === false) return elements
} return elements
} //$.grep是和jQuery里面一样的;
$.grep = function(elements, callback){
return filter.call(elements, callback)
} if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase()
}) // Define methods that will be available on all
// Zepto collections
$.fn = {
// Because a collection acts like an array
// copy over these useful array functions.
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
sort: emptyArray.sort,
indexOf: emptyArray.indexOf,
concat: emptyArray.concat, // `map` and `slice` in the jQuery API work differently
// from their array counterparts
//封装了一个fn方法, 改变了上下文为el, 参数列表为i, el;
map: function(fn){
return $($.map(this, function(el, i){ return fn.call(el, i, el) }));
},
//把当前选择的对象变成存数组对象;
slice: function(){
return $(slice.apply(this, arguments));
},
ready: function(callback){
// need to check if document.body exists for IE as that browser reports
// document ready when it hasn't yet created the body element
// readyRE === /complete|loaded|interactive/
//document的readyState状态加载完毕就直接执行,这东西是IE先有的,后来标准化了,所以没有什么兼容问题;
if (readyRE.test(document.readyState) && document.body) callback($)
//利用事件必定执行;
else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
return this
},
//把所有人切成数组,或者是某一个;
get: function(idx){
return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
},
toArray: function(){ return this.get() },
//为了跟jQ的接口统一
size: function(){
return this.length
},
remove: function(){
return this.each(function(){
if (this.parentNode != null)
this.parentNode.removeChild(this)
})
},
//这个只要返回值是false也停止迭代了,与jQ统一;
each: function(callback){
//只要call的东西有length而且有下标,只要是类数组都可以;
//是value和key, 不要忘记了;
emptyArray.every.call(this, function(el, idx){
return callback.call(el, idx, el) !== false
})
return this
},
filter: function(selector){
if (isFunction(selector)) return this.not(this.not(selector))
//迭代每一个选中的元素;, 过滤掉当前元素不符合选择器selector的元素;
return $(filter.call(this, function(element){
return zepto.matches(element, selector)
}))
},
//说明当前元素是HTMLELEMENTS,或者是NODES
add: function(selector,context){
//选择元素以后,匹配唯一;
return $(uniq(this.concat($(selector,context))))
},
//当前元素的第一个是否匹配选择符;
is: function(selector){
return this.length > 0 && zepto.matches(this[0], selector)
},
//not的效率挺低的;
not: function(selector){
var nodes=[];
//如果selector是函数
if (isFunction(selector) && selector.call !== undefined)
this.each(function(idx){
if (!selector.call(this,idx)) nodes.push(this)
})
else {
//如果是字符串就过滤当前匹配的到数组
var excludes = typeof selector == 'string' ? this.filter(selector) :
//如果是类数组而且有item属性,说明当前元素是HTMLELEMENTS,或者是NODES就转化成纯数组
//剩下的所有方式 new 一个zepto对象;
(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
//重新迭代当前的元素, 不在excludes里面的push到 nodes的结果集;
this.forEach(function(el){
if (excludes.indexOf(el) < 0) nodes.push(el)
})
}
return $(nodes)
},
//如果传的是对象的话, 把this里面所有包含selector的元素找出来,
//有点象filter...不过has是对当前的元素进行操作的, filter是对当前元素的子元素进行操作的;
has: function(selector){
return this.filter(function(){
return isObject(selector) ?
//一种是contains的意思
$.contains(this, selector) :
//如果是字符串就是找所有的子孙元素的长度
$(this).find(selector).size()
})
},
//
eq: function(idx){
return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
},
first: function(){
var el = this[0]
return el && !isObject(el) ? el : $(el)
},
last: function(){
var el = this[this.length - 1]
return el && !isObject(el) ? el : $(el)
}, find: function(selector){
var result, $this = this
//连选择器都没有, 那就不给你result了;
if (!selector) result = []
else if (typeof selector == 'object')
//从当前元素中选择出所有selector到的元素的交集;
//套了一堆循环,没有神马用感觉;
result = $(selector).filter(function(){
var node = this
return emptyArray.some.call($this, function(parent){
return $.contains(parent, node)
})
});
//如果只有一个,就返回一个zepto对象
else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
//否则返回一个数组
else result = this.map(function(){ return zepto.qsa(this, selector) })
return result
},
//没看懂,是我的话我就直接跑parentNode.. 这个context哪来干嘛用..
closest: function(selector, context){
//如果context没有值, selector为字符串
var node = this[0], collection = false
if (typeof selector == 'object') collection = $(selector)
//collection值是false的话,就zepto.matches(node ,selector)没匹配到就往里面走, 有匹配到的话就不往里面走...
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
node = node !== context && !isDocument(node) && node.parentNode
return $(node)
},
parents: function(selector){
var ancestors = [], nodes = this
while (nodes.length > 0)
nodes = $.map(nodes, function(node){
//让node成为node父级, 不是document, 在结果集里面没有node,就把它存入结果集;
if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
ancestors.push(node)
return node
}
});
//把结果集过滤出匹配selector的元素;
return filtered(ancestors, selector)
},
parent: function(selector){
//this.pluck('parentNode')的所有parentNode,取唯一 匹配selector,用的到吗, 这么多
return filtered(uniq(this.pluck('parentNode')), selector)
},
children: function(selector){
return filtered(this.map(function(){ return children(this) }), selector)
//return filtered( 把所有的选中的元素的子元素拉到数组 , 匹配选择器 )
},
contents: function() {
//把所有选中元素的所有都内容取出来,包含“节点”或者是“换行”节点等等;
return this.map(function() { return slice.call(this.childNodes) })
},
siblings: function(selector){
//如果没有selector就是匹配所有当前元素的兄弟元素
return filtered(this.map(function(i, el){
//把所有的元素的parentNode的children取出来,过滤掉不是当前的资源税
return filter.call(children(el.parentNode), function(child){ return child!==el })
}), selector) //通过选择器选中;
},
//把内容清空;
empty: function(){
return this.each(function(){ this.innerHTML = '' })
},
// `pluck` is borrowed from Prototype.js
//和underscore一样的,抄自prototype;
pluck: function(property){
return $.map(this, function(el){ return el[property] })
},
show: function(){
return this.each(function(){
//先直接把display清空
this.style.display == "none" && (this.style.display = '')
//为了以防万一,他的值还没改;
if (getComputedStyle(this, '').getPropertyValue("display") == "none")
//显示默认的display值;
this.style.display = defaultDisplay(this.nodeName)
})
},
//这之前加一堆东西,然后删除自己;
replaceWith: function(newContent){
return this.before(newContent).remove()
},
//DOM方法还没结束啊,这个看完去复习jQuery,然后去看angular;一步一步来吧,进步太慢了;
wrap: function(structure){
var func = isFunction(structure)
if (this[0] && !func)
var dom = $(structure).get(0),
clone = dom.parentNode || this.length > 1 return this.each(function(index){
$(this).wrapAll(
func ? structure.call(this, index) :
clone ? dom.cloneNode(true) : dom
)
})
}, //这个只对第一个元素进行操作,dom修改;
wrapAll: function(structure){
if (this[0]) {
$(this[0]).before(structure = $(structure))
var children
// drill down to the inmost element
while ((children = structure.children()).length) structure = children.first()
$(structure).append(this)
}
return this
},
wrapInner: function(structure){
var func = isFunction(structure)
return this.each(function(index){
//保存当前元素;
//保存所有当前节点;
var self = $(this), contents = self.contents(),
//structure可能是字符串,但是没事的,wrapAll里面会进行处理;
dom = func ? structure.call(this, index) : structure;
//避免出错吧;
contents.length ? contents.wrapAll(dom) : self.append(dom)
});
//TODO 如果参数的 structure是一个DOM节点呢, 这个节点并不会被复制哦,
},
//就是把这个元素的父级删掉么么哒;
unwrap: function(){
this.parent().each(function(){
$(this).replaceWith($(this).children())
})
return this
},
//这个是复制事件和子元素的
clone: function(){
return this.map(function(){ return this.cloneNode(true) })
}, hide: function(){
return this.css("display", "none")
},
toggle: function(setting){
//迭代元素;
return this.each(function(){
var el = $(this)
// setting === undefined ? el.css("display") == "none" : setting 是none就show 不是none就undefined ,undefined又走hide
// 批语:没事瞎JB绕
;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
})
}, //把所有选中的元素额上个元素匹配出来到一个数组里面去;
prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
html: function(html){
return 0 in arguments ?
this.each(function(idx){
var originHtml = this.innerHTML;
/*我擦
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}
*/
//这边做了处理,如果 html是function 就执行function, 传一个index和originHtml;
$(this).empty().append( funcArg(this, html, idx, originHtml) )
//$(this).empty().append( html ),这样不行吗;
}) :
//返回第一个元素的innerHTML
(0 in this ? this[0].innerHTML : null)
},
text: function(text){
return 0 in arguments ?
this.each(function(idx){
/*
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}
一般来说,只要arg不是function类型都跟么走一样样的
*/
var newText = funcArg(this, text, idx, this.textContent)
this.textContent = newText == null ? '' : ''+newText
}) :
(0 in this ? this[0].textContent : null)
}, //到达属性模块;
//自定义
attr: function(name, value){
var result
return (typeof name == 'string' && !(1 in arguments)) ?
//判断元素是否是节点元素
(!this.length || this[0].nodeType !== 1 ? undefined :
//获取属性
(!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
) :
//设置属性
this.each(function(idx){
if (this.nodeType !== 1) return
if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
})
},
//走设置自定义属性,不给值;
removeAttr: function(name){
return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) })
},
//节点属性
prop: function(name, value){
name = propMap[name] || name
return (1 in arguments) ?
this.each(function(idx){
this[name] = funcArg(this, value, idx, this[name])
}) :
(this[0] && this[0][name])
},
//jQuery为了让库代码更节俭通过access跑属性方法,zepto更加直接
//jQuery的data为放在缓存里面的;
data: function(name, value){
//"大写字母" ==>> 变成 ==> "-大写字母", 在变成小写
var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase() var data = (1 in arguments) ?
this.attr(attrName, value) :
this.attr(attrName) //返回数据,
return data !== null ? deserializeValue(data) : undefined
},
val: function(value){
return 0 in arguments ?
this.each(function(idx){
//设置
this.value = funcArg(this, value, idx, this.value)
}) :
//返回值 如果元素是select 就把选中的元素过滤出来, 并获取value;
(this[0] && (this[0].multiple ?
$(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
//直接返回值,话说这东西的确没有兼容问题么么哒
this[0].value)
)
},
//coordinates : 协调
//知识点:因为relative是相对定位的,不知道父级是绝对定位还是正常的,所以通过getBoundRClientRect获取父级的位置
//把值给界面的绝对定位值, 让元素根据父级相对定位;
//(为什么这么做),如果是让他绝对定位的话,这个元素会受到所有父级的影响, 所以不要设置绝对定位最好(就减少了JS的值计算),
//让他相对父级进行值计算, 根据界面定位;
//启发:如果界面有太对的absolute,界面位置的可通性就太差了,只要设置相对定位,根据父级计算left,和top;也是极好的;
//知识点1:getBoundRClientRect是的获取的top是包含margin值的值(总体的说就是相对界面(html)的位置);
offset: function(coordinates){
// coordinates 是一个方法 或者是一个 对象;
// coordinates 的值是这个object相对页面的left和top, zepto会把obj相对父级元素定位;
if (coordinates) return this.each(function(index){
var $this = $(this),
coords = funcArg(this, coordinates, index, $this.offset()),
//relative是相对父级进行定位的;
//parentOffse也是相对界面定位的, 所以没有什么问题的
parentOffset = $this.offsetParent().offset(),
props = {
top: coords.top - parentOffset.top,
left: coords.left - parentOffset.left
} if ($this.css('position') == 'static') props['position'] = 'relative'
$this.css(props)
})
if (!this.length) return null
var obj = this[0].getBoundingClientRect()
return {
left: obj.left + window.pageXOffset,
top: obj.top + window.pageYOffset,
width: Math.round(obj.width),
height: Math.round(obj.height)
}
}, css: function(property, value){
//就是length就只有1个,获取属性;
if (arguments.length < 2) {
var element = this[0], computedStyle = getComputedStyle(element, '')
if(!element) return
if (typeof property == 'string')
//如果有行内样式就快点返回行内样式(!important怎么办), 否则通过getPropertyValue获取
return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
else if (isArray(property)) {
//如果想要获取一对属性
var props = {}
$.each(isArray(property) ? property: [property], function(_, prop){
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
})
return props
}
} var css = ''
if (type(property) == 'string') {
if (!value && value !== 0)
//删除属性
this.each(function(){ this.style.removeProperty(dasherize(property)) })
else
//设置
css = dasherize(property) + ":" + maybeAddPx(property, value)
} else {
//是对象的话;
for (key in property)
if (!property[key] && property[key] !== 0)
this.each(function(){ this.style.removeProperty(dasherize(key)) })
else
css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
};
return this.each(function(){ this.style.cssText += ';' + css })
},
//获取当前相对父级的index或者传进来的元素的index;
index: function(element){
return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
},
//
hasClass: function(name){
if (!name) return false
// Array.some的第二个参数为里面的this;
return emptyArray.some.call(this, function(el){
//直接把 正则作为this了,我勒个去;
return this.test(className(el));
}, classRE(name));
}, addClass: function(name){
if (!name) return this
return this.each(function(idx){
//迭代this元素
classList = []
var cls = className(this), newName = funcArg(this, name, idx, cls)
newName.split(/\s+/g).forEach(function(klass){
//把所有传进来的class通过空格分开;
//把所有的class保存到数组里面;
if (!$(this).hasClass(klass)) classList.push(klass)
}, this/*这个this为上下文*/);
//把元素的新的class和原来的class拼合起来再赋值;
classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
})
},
removeClass: function(name){
return this.each(function(idx){
//如果没有传值就把所有的class清空;
if (name === undefined) return className(this, '')
classList = className(this)
//传进来的可能是函数, 把class结果获取出来;
funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
//生成动态正则匹配替换成空;
classList = classList.replace(classRE(klass), " ")
});
//trim, 去除两边的空格;
className(this, classList.trim())
})
},
toggleClass: function(name, when){
if (!name) return this
return this.each(function(idx){
var $this = $(this),
//因为这些都是迭代每一个元素, 所以获取设置的class还是要放在里面比较好;
names = funcArg(this, name, idx, className(this));
names.split(/\s+/g).forEach(function(klass){
(when === undefined ? !$this.hasClass(klass) : when) ?
$this.addClass(klass) : $this.removeClass(klass)
// $this.hasClass( klass ) ? $this.removeClass(klass) : $this.addClass( klass );
/*三目的写法 ( 三目的写法不同, 意义也是不相同的 );
一:
yes ? a :
yes1 ? b :
yes2 ? c :
yes3 ? d : default;
=== if( yes ) {
a
}else if( yes1 ) {
b
}else if( yes2 ) {
c
}else if( yes3 ) {
d
};
二:
( yes ? a : b ) ? c : d
====
var bVal;
if( yes ) {
temp = a;
}else{
temp = b;
};
if( bVal ) {
c;
}else{
d
}
*/
});
});
},
scrollTop: function(value){
if (!this.length) return
var hasScrollTop = 'scrollTop' in this[0]
//获取的话直接返回scrollTop, 如果当前元素没有滚动条, 就返回相对整个界面的pageYOffset;
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
return this.each(hasScrollTop ?
//当前元素有滚动高度, 就直接设置,
//如果没有滚动高度, 就设置为整个界面的滚动高度;
function(){ this.scrollTop = value } :
function(){ this.scrollTo(this.scrollX, value) })
},
scrollLeft: function(value){
if (!this.length) return
var hasScrollLeft = 'scrollLeft' in this[0]
if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
return this.each(hasScrollLeft ?
function(){ this.scrollLeft = value } :
function(){ this.scrollTo(value, this.scrollY) })
},
position: function() {
if (!this.length) return var elem = this[0],
// Get *real* offsetParent //这个元素一定是相对定位 “relative”或者是“absolute”定位的;
offsetParent = this.offsetParent(),
// Get correct offsets
//offset是相对整个文档界面的left和top, 以及width和height;
offset = this.offset(),
//父级的相对HTML的offset(left, top, height, width);
//rootNodeRE是指BODY或者是HTML元素;
parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
//如果这个元素的margin-top是正的无限大,那么offset.top也是正的无限大, 是相对的;
//这个获取的offset是相对上一个相对或者绝对定位的位置 ; 这个offset值是包含margin的所以要把margin减去;
//知识点1: nodes[0].offsetLeft || nodes[0].offsetTop是包含margin的,从元素的 border开始(居然忘记了);
//知识点2: absolute或者relative的定位是从contentBox开始的
//而zepto的offset()是相对界面的left,和top, 最后的值要是元素的margin到上一个定位元素的contentBox(标准定义也是这样的);
offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 // Add offsetParent borders
parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 // Subtract the two offsets
return {
//offset.top - parentOffset.left - el.margin-top - parentOffset.border-left-width;
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
//评论;因为平台兼容问题,position根据标准等问题;直接把获取当前元素和父级元素的offset;
//==> el.offset.top - parent.offset.top - el.style.marginTop - parent.style.borderTop;
//TODO这个position为什么不通过el.css("position")进行获取呢?
},
offsetParent: function() {
return this.map(function(){
var parent = this.offsetParent || document.body;
//存在这个parent元素, 不是documentElement( html节点 ) 而且这个元素的样式"position"值不为"static";
/*<!--
TODO : 可能存在一个元素的offsetParent的position值为static?
-->*/
while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
parent = parent.offsetParent; return parent
})
}
} // for now
$.fn.detach = $.fn.remove
/*
//不包含滚动条和边框的宽度;
window.innerWidth
//包含滚动条和边框;
window.outerWidth
window.innerHeight
window.outerHeight
document.documentElement.clientHeight
//卧槽,这个比window.innerWidth少了17px..
document.documentElement.clientWidth
document.documentElement.scrollWidth
document.documentElement.scrollTop
document.documentElement.scrollHeight
*/
// Generate the `width` and `height` functions
;['width', 'height'].forEach(function(dimension){
//把第一个字符变成大写的给dimensionProperty;
var dimensionProperty =
dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){
var offset, el = this[0]
//对window和document和其他节点元素分别处理; //如果是window就直接返回window.innerWidth
if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
//通过offset()获取的值返回;
(offset = this.offset()) && offset[dimension]; //设置值
else return this.each(function(idx){
el = $(this)
el.css(dimension, funcArg(this, value, idx, el[dimension]()))
});
};
}); //迭代node的所有子元素
function traverseNode(node, fun) {
fun(node)
//node的childNodes时包含空节点的;
for (var i = 0, len = node.childNodes.length; i < len; i++)
traverseNode(node.childNodes[i], fun)
//如果是我写的话,我会这样;
/*
if( node.childNodes.length ) {
for (var i = 0, len = node.childNodes.length; i < len; i++);
traverseNode(node.childNodes[i], fun);
}
*/
} // Generate the `after`, `prepend`, `before`, `append`,
// `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
// adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ];
adjacencyOperators.forEach(function(operator, operatorIndex) {
/*
0%2
==>>0
1%2
==>>1
2%2
==>>0
3%2
==>>1
*/
var inside = operatorIndex % 2 //=> prepend, append $.fn[operator] = function(){
// arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
var argType,
/*
把传的参数调整一下, 是字符串就转化成节点;
*/
nodes = $.map(arguments, function(arg) {
argType = type(arg)
return argType == "object" || argType == "array" || arg == null ?
arg : zepto.fragment(arg)
}),
parent,
//如果当前选中的元素有多个, 就把传的参数进行复制;
copyByClone = this.length > 1
//没参数进来就跳走;
if (nodes.length < 1) return this return this.each(function(_, target){
//如果是append或者是prepend那么parent就改成targetparent,否则parent就不要变了就是this;
parent = inside ? target : target.parentNode //convert all methods to a "before" operation
// [ 'after', 'prepend', 'before', 'append' ];
target = operatorIndex == 0 ? target.nextSibling :
operatorIndex == 1 ? target.firstChild :
operatorIndex == 2 ? target :
null //只要是包含都是true值;
var parentInDocument = $.contains(document.documentElement, parent); //把所有传进来的node跑一遍;
nodes.forEach(function(node){
//基础: if( a ){ console.log( a ) }else if( a )console.log(a) //true 就一个;
if (copyByClone) node = node.cloneNode(true)
else if (!parent) return $(node).remove() //如果 operator符是after ==>> parent为targer.parentNode; target为 target.nextElementSibling;
parent.insertBefore(node, target);
//TODO, 不能 traverseNode parent或者是target, 必须traverseNode node才行, 把node里面的script标签执行;
if (parentInDocument) traverseNode(node, function(el){
//判断方法;
if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
(!el.type || el.type === 'text/javascript') && !el.src)
//全局eval跑javascirpt代码;
window['eval'].call(window, el.innerHTML)
})
})
})
} // after => insertAfter
// prepend => prependTo
// before => insertBefore
// append => appendTo
//..这个看了能不晕吗..逻辑就是把传进来的html作为相对的节点; this为参数重新传过去;
$.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
$(html)[operator](this)
return this
}
}) zepto.Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace
zepto.uniq = uniq
zepto.deserializeValue = deserializeValue
$.zepto = zepto; window.Zepto = Zepto
window.$ === undefined && (window.$ = Zepto) //到达事件模块;
;(function($){
var _zid = 1, undefined,
slice = Array.prototype.slice,
isFunction = $.isFunction,
isString = function(obj){ return typeof obj == 'string' },
//保存所有元素对应的事件列表;
handlers = {},
specialEvents={
"click" : "MouseEvents",
"mousedown" : "MouseEvents",
"mouseup" : "MouseEvents",
"mousemove" : "MouseEvents"
},
focusinSupported = 'onfocusin' in window,
focus = { focus: 'focusin', blur: 'focusout' },
hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }; specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents' //保存一个元素的el;
function zid(element) {
return element._zid || (element._zid = _zid++)
}; //迭代寻找handler;
//在el对应的zid, 在handlers里面, 通过event, 或者fn, 或者selector 匹配到所有的对应函数;
function findHandlers(element, event, fn, selector) {
event = parse(event)
if (event.ns) var matcher = matcherFor(event.ns) //过滤所有的合适的handlers;
return (handlers[zid(element)] || []).filter(function(handler) {
return handler //handler前提要存在
&& (!event.e || handler.e == event.e) //没有event.e就走下一个, 有event.e的话event.e要等于 handler.e;
&& (!event.ns || matcher.test(handler.ns)) //没有event.ns就走下一个, 有event.ns的话event.ns要等于 hanler.ns;
&& (!fn || zid(handler.fn) === zid(fn)) //没有fn就走下一个, 有fn的话fn.zid要等于 handler.fn.zid;
&& (!selector || handler.sel == selector) //没有selector就走下一个, 有selector的话selector要等于 handler.sel;
})
}; function parse(event) {
//返回 一个对象 这个对象包含 ev和 ns 命名空间;
var parts = ('' + event).split('.')
return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}; //匹配正则, 开头或者空格 或者是 结尾或者空格的字符串;
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}; function eventCapture(handler, captureSetting) {
//存在事件代理;
return handler.del &&
//冒泡的focusein不支持 //事件是focus或者blur;
(!focusinSupported && (handler.e in focus)) ||
//或者接着 去captureSetting的布尔值;
!!captureSetting
}; //mouse事件的替换; focusinSupported;
function realEvent(type) {
return hover[type] || (focusinSupported && focus[type]) || type
}; //zip是正常的绑定事件, 只是对事件兼容进行了处理, 所有保存的事件在handlers下都可以找到:
//$("body").bind("click",function(){console.log(1)});
//那么 data, selector delegator capture的值全为undefined
function add(element, events, fn, data, selector, delegator, capture) {
//handlers保存在内部变量, 保存每一个element对应的zid的 handlers, 以后可以找到这个handlers的handler进行操作;
var id = zid(element), set = (handlers[id] || (handlers[id] = []))
events.split(/\s/).forEach(function(event){
//如果是函数,就把fn放到DOM加载完毕以后执行;
if (event == 'ready') return $(document).ready(fn);
//Object {e: "click", ns: ""} 这个是parse以后的event对象;
var handler = parse(event)
handler.fn = fn
handler.sel = selector
//对fn进行重写;
// emulate mouseenter, mouseleave
if (handler.e in hover) fn = function(e){
var related = e.relatedTarget
if (!related || (related !== this && !$.contains(this, related)))
return handler.fn.apply(this, arguments)
}
handler.del = delegator;
//设置回调, delegator的 回调对象优先, fn这个对象的优先级相对较低;
var callback = delegator || fn;
//这个就是元素绑定的事件;
handler.proxy = function(e) {
//对事件对象进行兼容处理;
//如果compatible就传一个(e), 那么compatible就返回这个e, 没有任何改变;
e = compatible(e);
//isImmediatePropagationStopped都支持的吗?;
if (e.isImmediatePropagationStopped()) return;
e.data = data
//通过这个桥接 执行回调, 回调的上下文为element; _args是什么鸟东西;
var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args));
//如果这个返回值是false就执行取消默认事件和事件冒泡, 和jQ一样样的;
if (result === false) e.preventDefault(), e.stopPropagation();
//这个返回有什么用..个人认为这个是习惯性返回;
return result;
};
//handler.i为当前的length值,就是该元素对应的索引值;
handler.i = set.length;
/*
{
del: undefined, //
e: "click",
ns: "",
fn: function (){console.log(1)},
i: 0,
proxy: function (e){}
*/
set.push(handler);
if ('addEventListener' in element)
//realEvent(handler.e), 因为可能有一些事件不支持,对事件进行兼容处理hover[type] || (focusinSupported && focus[type]) || type
element.addEventListener(realEvent(handler.e), handler.proxy/*这个是hanler的引用,如果要修改handler.proxy也很简单*/, eventCapture(handler, capture))
});
}; function remove(element, events, fn, selector, capture){
var id = zid(element)
;(events || '').split(/\s/).forEach(function(event){
//就是通过event或者fn或者是selector寻找handler,
//只要handler找到了, 绑定的函数的详细信息就找到了;
findHandlers(element, event, fn, selector).forEach(function(handler){
// handlers[id]是所有事件的数组; handler.i是当前数组的index;
delete handlers[id][handler.i]
//因为所有的事件都是保存在handlers[zid]里面, 可以很快的通过"event或者fn以及selector"找到需要的信息,再进行removeEventListener;
if ('removeEventListener' in element)
element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
});
});
}; //可以直接通过方法进行调用;
$.event = { add: add, remove: remove }; //改变文件的上下文;
$.proxy = function(fn, context) {
//保存第二个开始的所有参数;
var args = (2 in arguments) && slice.call(arguments, 2)
if (isFunction(fn)) { var proxyFn = function(){
return fn.apply( context/*上下文*/, args /*有参数的话就concat*/? args.concat(slice.call(arguments)) : arguments );
};
//为proxy设置_zid;
proxyFn._zid = zid(fn);
return proxyFn;
} else if (isString(context)) {
if ( args ) {
//修正args参数
args.unshift(fn[context], fn)
//这个相当于 $.proxy( Array.prototype.slice.call(args) );
return $.proxy.apply(null, args)
} else {
//用fn[context]执行 fn;
return $.proxy(fn[context], fn)
}
} else {
throw new TypeError("expected function")
}
} //bind和on一摸一样
$.fn.bind = function(event, data, callback){
return this.on(event, data, callback)
}; //unbind和off一摸一样;
$.fn.unbind = function(event, callback){
return this.off(event, callback)
}; $.fn.one = function(event, selector, data, callback){
return this.on(event, selector, data, callback, 1)
}; var returnTrue = function(){return true},
returnFalse = function(){return false},
ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/,
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
}; //event为新的事件对象 后者event不支持isXXXX属性的话;
function compatible(event, source) {
//事件不支持isDefaultPrevented这个方法的话;
//这样说明event对象也不支持isImmediatePropagationStopped和isPropagationStopped;
if (source || !event.isDefaultPrevented) { //source有的话就是有, source没有的话把event给source;
source || (source = event); $.each(eventMethods, function(name, predicate) {
//保存原来的方法(//preventDefault //stopImmediatePropagation //stopPropagation);
var sourceMethod = source[name];
event[name] = function() {
//设置为真值;
this[predicate] = returnTrue;
//
return sourceMethod && sourceMethod.apply(source, arguments);
};
//手动设置(//isDefaultPrevented //isImmediatePropagationStopped //isPropagationStopped);
event[predicate] = returnFalse;
});
/*
函数的重载(个人认为么么哒);
function wrapFn(target, another) {
var temp = target;
target = function() {
temp.apply(temp, arguments);
another();
};
return target;
};
var fn = function() {};
fn = wrapFn( fn , fn1);
fn();
*/
//
//event.defaultPrevented //==>> https://developer.mozilla.org/en-US/docs/Web/API/event.defaultPrevented
//Summary
//Returns a boolean indicating whether or not event.preventDefault() was called on the event.
//Note: You should use this instead of the non-standard, deprecated getPreventDefault() method (see bug 691151). if (source.defaultPrevented !== undefined ? source.defaultPrevented : //如果事件的source.defaultPrevented不是undefined的话returnValue;
'returnValue' in source ? source.returnValue === false : //如果是IE的事件机制.returnValue 是false的话走进去;
source.getPreventDefault && source.getPreventDefault()) //默认事件是否被取消默认事件的兼容处理;
event.isDefaultPrevented = returnTrue;
};
return event;
}; //新建event;
function createProxy(event) {
var key, proxy = { originalEvent: event }
for (key in event)
// ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/, 为什么要避免returnValue和 layerX和 layerY呢;
if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key] //复制事件对象; //处理事件对象的兼容问题;
return compatible(proxy, event)
}; $.fn.delegate = function(selector, event, callback){
return this.on(event, selector, callback)
}; $.fn.undelegate = function(selector, event, callback){
return this.off(event, selector, callback)
} //JQ高版本不存在live和 die方法了;
$.fn.live = function(event, callback){
$(document.body).delegate(this.selector, event, callback)
return this
}
$.fn.die = function(event, callback){
$(document.body).undelegate(this.selector, event, callback)
return this
} $.fn.on = function(event, selector, data, callback, one){
var autoRemove, delegator, $this = this
//如果事件不是字符串
/*
是这一种情况下 :
{
"click" : function() {},
"touchend" : function() {}
}
*/
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.on(type, selector, data, fn, one)
})
return $this
};
//调整正确的参数 //判断selector不是正确的参数,把selector设置为undefined
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = data, data = selector, selector = undefined
//判断data是function,把data设置为undefined
if (isFunction(data) || data === false)
callback = data, data = undefined if (callback === false) callback = returnFalse //对当前的所有元素进行迭代;
return $this.each(function(_, element){
//只执行一次的话;
if (one) autoRemove = function(e){
//清除当前元素的事件;
remove(element, e.type, callback)
return callback.apply(this, arguments)
}; //如果有事件代理的话
if (selector) delegator = function(e){
//对e.target匹配的最近的selector;
var evt, match = $(e.target).closest(selector, element).get(0);
//match还能match到element..
if (match && match !== element) {
//对事件进行添加属性;
evt = $.extend(createProxy(e), {currentTarget: match/*target就是这个了*/, liveFired: element});//liveFired为绑定的element
//对函数进行重载;
return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
};
}; add(element, event, callback, data, selector, delegator || autoRemove)
});
}; $.fn.off = function(event, selector, callback){
var $this = this
if (event && !isString(event)) {
//对对象进行处理, 加载自己;
$.each(event, function(type, fn){
$this.off(type, selector, fn)
})
return $this
}; //对参数进行处理;
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = selector, selector = undefined if (callback === false) callback = returnFalse //
return $this.each(function(){
remove(this, event, callback, selector)
});
}; $.fn.trigger = function(event, args){
event = (isString(event) ||
//如果是空对象就新建一个事件对象, 否则就对这个对象进行兼容处理;
$.isPlainObject(event)) ?
$.Event(event) : compatible(event)
event._args = args
//对每一个元素进行处理;
return this.each(function(){
// items in the collection might not be DOM elements
if('dispatchEvent' in this) this.dispatchEvent(event)
//手动触发事件;
else $(this).triggerHandler(event, args)
});
}; // triggers event handlers on current element just as if an event occurred, //触发让事件发生;
// doesn't trigger an actual event, doesn't bubble 不会触发真正的事件, 不会事件冒泡
$.fn.triggerHandler = function(event, args) {
var e, result
//每一个元素都进行处理;
this.each(function(i, element){
//新建新的event或者是直接用模拟的event触发事件;
e = createProxy(isString(event)/*为什么传进来的会是字符串*/ ? $.Event(event) : event)
e._args = args;
e.target = element;
//通过element的 event.type或者 event找到 事件函数, 直接执行hadler.proxy( e )// e为参数;
$.each(findHandlers(element, event.type || event), function(i, handler){
result = handler.proxy(e);
if (e.isImmediatePropagationStopped()) return false;
});
});
return result;
}; //使用快捷方法直接绑定到$.fn上面去;
// shortcut methods for `.bind(event, fn)` for each event type
;('focusin focusout load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
$.fn[event] = function(callback) {
return callback ?
this.bind(event, callback) :
this.trigger(event)
}
}) ;['focus', 'blur'].forEach(function(name) {
$.fn[name] = function(callback) {
if (callback) this.bind(name, callback)
else this.each(function(){
try { this[name]() }
catch(e) {}
})
return this
}
}) //新建事件模型;
$.Event = function(type, props) {
if (!isString(type)) props = type, type = props.type
var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
event.initEvent(type, bubbles, true)
return compatible(event)
} })(Zepto); ;(function($){
//jsonID一看就知道是递增的
var jsonpID = 0,
//为了浏览器更快的找到document,不必一层层往上最后在window下找到document
document = window.document,
key,
name,
//匹配闭合的<script>标签, as like <script src="1213123">sdfsdf</script>;
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
//匹配text/javascript或者application/javascript;
scriptTypeRE = /^(?:text|application)\/javascript/i,
//匹配text/xml 和 application/xml
xmlTypeRE = /^(?:text|application)\/xml/i,
//
jsonType = 'application/json',
//
htmlType = 'text/html',
//匹配所有空标签;
blankRE = /^\s*$/ // trigger a custom event and return false if it was cancelled
function triggerAndReturn(context, eventName, data) {
var event = $.Event(eventName)
$(context).trigger(event, data)
return !event.isDefaultPrevented()
} // trigger an Ajax "global" event
function triggerGlobal(settings, context, eventName, data) {
if (settings.global) return triggerAndReturn(context || document, eventName, data)
} // Number of active Ajax requests
$.active = 0 function ajaxStart(settings) {
//如果设置里有global, 而且是第一次发送ajax, 就手动触发document的"ajaxStart";
if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}
function ajaxStop(settings) {
//和上面的一模一样;
if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
} // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
function ajaxBeforeSend(xhr, settings) {
var context = settings.context
//触发options里面的beforeSend自定义事件;
if (settings.beforeSend.call(context, xhr, settings) === false ||
//触发dcoument的ajaxBeforeSend事件,
//或者是options.context的ajaxBeforeSend事件;
triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
return false; //触发document或者是指定上下文的"ajaxSend"事件;
triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}
function ajaxSuccess(data, xhr, settings, deferred) {
var context = settings.context, status = 'success'
settings.success.call(context, data, status, xhr)
if (deferred) deferred.resolveWith(context, [data, status, xhr])
triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
ajaxComplete(status, xhr, settings);
}
// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings, deferred) {
var context = settings.context
settings.error.call(context, xhr, type, error)
if (deferred) deferred.rejectWith(context, [xhr, type, error])
triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
ajaxComplete(type, xhr, settings)
}
// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
function ajaxComplete(status, xhr, settings) {
var context = settings.context
settings.complete.call(context, xhr, status)
triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
ajaxStop(settings)
} // Empty function, used as default callback
function empty() {} $.ajaxJSONP = function(options, deferred){
//如果没有type就会走ajax的请求了;
if (!('type' in options)) return $.ajax(options) //保存回调的设置;
var _callbackName = options.jsonpCallback,
//这个callback要是等到script加载完毕以后才执行的,现状可能没有这个函数
//如果现在有回调,而且回调是函数 就立即执行
callbackName = ($.isFunction(_callbackName) ?
//_callbackName为假值(false,null,undefined,""..)的时候,回调执行返回为自己定义递增的回调名字;
_callbackName() /*TODO:这个还要跑一下才行?*/ : _callbackName) || ('jsonp' + (++jsonpID)),
//新建标签
script = document.createElement('script'),
//这个要保存当前的回调;
originalCallback = window[callbackName],
responseData,
//取消的桥接(传送器);,超时("timeout")或者是错误("error")的时候触发的消息;
abort = function(errorType) {
$(script).triggerHandler('error', errorType || 'abort')
},
xhr = { abort: abort },
//如果有传这个option.abortTimeout ,那么超时就取消;
abortTimeout //TODO:为什么要把xhr放进去, xhr只是一个对象啊
if (deferred) deferred.promise(xhr) //要先绑定事件, 绑定加载和失败事件
$(script).on('load error', function(e, errorType){
//取消setTimeout;
clearTimeout(abortTimeout); //删除事件,从dom中删除;
$(script).off().remove() if (e.type == 'error' || !responseData) {
//统一的事件处理, 方便添加各种自定义的事件
ajaxError(null, errorType || 'error', xhr, options, deferred)
} else {
//统一的事件处理, 方便添加各种自定义的事件
ajaxSuccess(responseData[0], xhr, options, deferred)
} //这个为什么用callback?为了思路更加清楚?才把callback保存起来,然后统一运行?
//把回调重新赋值到window下面然后用callback跑起来;
window[callbackName] = originalCallback
if (responseData && $.isFunction(originalCallback))
originalCallback(responseData[0]) originalCallback = responseData = undefined
}); //执行自定义事件;
if (ajaxBeforeSend(xhr, options) === false) {
//事件执行的返回为false就会把执行中断;
abort('abort')
return xhr
}
//JSONP就是一个链接放到DOM中;服务器会把返回的数据放在请求的回调,让会让回调执行, 服务器不管本地是否有回调这个东西, 负责执行就好了; //覆盖(假冒)了当前的回调,把返回的结果保存起来了;
window[callbackName] = function(){
responseData = arguments
}; // ?xx=? ==》》 ?xx=callbackName;
//替换
script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName) //动态添加节点;
document.head.appendChild(script) //如果有超时这个选项, 就启动一个定时器, 到时间了取消(abort);
if (options.timeout > 0) abortTimeout = setTimeout(function(){
abort('timeout')
}, options.timeout) return xhr
}; //设置以后就都变成了全局变量了
$.ajaxSettings = {
// Default type of request
type: 'GET',
// Callback that is executed before request
//这些一堆东西基本上都要设置;
beforeSend: empty,
// Callback that is executed if the request succeeds
success: empty,
// Callback that is executed the the server drops error
error: empty,
// Callback that is executed on request complete (both: error and success)
complete: empty,
// The context for the callbacks
context: null,
// Whether to trigger "global" Ajax events
global: true,
// Transport ,好屌的传送器, 只要这样就好了,没有任何兼容问题;
xhr: function () {
return new window.XMLHttpRequest()
},
// MIME types mapping
// IIS returns Javascript as "application/x-javascript"
accepts: {
script: 'text/javascript, application/javascript, application/x-javascript',
json: jsonType,
xml: 'application/xml, text/xml',
html: htmlType,
text: 'text/plain'
},
// Whether the request is to another domain
//$.ajaxSettings.crossDomain = true;jQuery也有这个东西, 打开默认的跨域ajax设置;
crossDomain: false,
// Default timeout
timeout: 0,
// Whether data should be serialized to string
processData: true,
// Whether the browser should be allowed to cache GET responses
cache: true
} function mimeToDataType(mime) {
if (mime) mime = mime.split(';', 2)[0]
return mime && ( mime == htmlType ? 'html' :
mime == jsonType ? 'json' :
scriptTypeRE.test(mime) ? 'script' :
xmlTypeRE.test(mime) && 'xml' ) || 'text'
} function appendQuery(url, query) {
if (query == '') return url
return (url + '&' + query).replace(/[&?]{1,2}/, '?')
} // serialize payload and append it to the URL for GET requests
function serializeData(options) {
//如果发送的数据是JOSON格式就序列化;
if (options.processData && options.data && $.type(options.data) != "string")
options.data = $.param(options.data, options.traditional)
//默认的option.type如果被用户的type覆盖的话 , 或者type就是"get"就把option.data转成url请求的格式
//xx.html?xx=11&yy=2&zz=3 这样的;
if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
options.url = appendQuery(options.url, options.data), options.data = undefined
} //主流程;
$.ajax = function(options){
var settings = $.extend({}, options || {}),
//如果有引用了Deferred延迟对象, 就会返回延迟对象;
deferred = $.Deferred && $.Deferred();
//把所有用户没有设置的默认设置复制到设置上面;
for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key] //触发document上的ajaxStart事件;
ajaxStart(settings) //中断检测是否跨域, 被设置settings.crossDomain这个属性;
if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
RegExp.$2 != window.location.host //
if (!settings.url) settings.url = window.location.toString(); //修正发送的数据;
serializeData(settings); var dataType = settings.dataType, ///\?.+=\?/.test("http://ww.xx.com/?sdfsdf=?sdfs") ==>> ture;
hasPlaceholder = /\?.+=\?/.test(settings.url)
if (hasPlaceholder) dataType = 'jsonp' //是否添加时间戳;
if (settings.cache === false || (
(!options || options.cache !== true) &&
('script' == dataType || 'jsonp' == dataType)
))
settings.url = appendQuery(settings.url, '_=' + Date.now()) //如果是jsonp的话;
if ('jsonp' == dataType) {
//请求的地址没有回调参数的话, 要根据callback设定一个回调的名字;
if (!hasPlaceholder)
settings.url = appendQuery(settings.url,
settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
return $.ajaxJSONP(settings, deferred)
}; /**
* accepts: {
script: 'text/javascript, application/javascript, application/x-javascript',
json: jsonType,
xml: 'application/xml, text/xml',
html: htmlType,
text: 'text/plain'
*/
var mime = settings.accepts[dataType],
headers = { },
setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
xhr = settings.xhr(),
nativeSetHeader = xhr.setRequestHeader,
abortTimeout //JSONP也有这东西;
if (deferred) deferred.promise(xhr) //设置请求头;
if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest') //设置返回的类型;(告诉服务器,客户端要的数据类型);
/*
* MIME意为多目Internet邮件扩展,它设计的最初目的是为了在发送电子邮件时附加多媒体数据,让邮件客户程序能根据其类型进行处理。
其实就是作为附件进行大数据传输!
* */
setHeader('Accept', mime || '*/*')
//如果用户有定义了返回的mime类型, 就重写mime;
if (mime = settings.mimeType || mime) {
if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
xhr.overrideMimeType && xhr.overrideMimeType(mime)
}; //是post的话要设置默认的 content-type 到请求头,默认的请求头是表单(FORM)的方式application/x-www-form-unlencoded;
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded') //在设置一些用户自定义的请求头;
if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
xhr.setRequestHeader = setHeader xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
//直接去除事件;
xhr.onreadystatechange = empty
clearTimeout(abortTimeout)
var result, error = false;
//处理兼容问题;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
//
dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
//请求的返回的Text,还有responseXML和 responseBinnary这些东西;
result = xhr.responseText try {
// http://perfectionkills.com/global-eval-what-are-the-options/
//全局eval返回的数据;
if (dataType == 'script') (1,eval)(result)
else if (dataType == 'xml') result = xhr.responseXML
else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
} catch (e) { error = e } if (error) ajaxError(error, 'parsererror', xhr, settings, deferred)
//成功的事件;
else ajaxSuccess(result, xhr, settings, deferred)
} else {
ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred)
}
}
} //触发自定义事件;
if (ajaxBeforeSend(xhr, settings) === false) {
xhr.abort()
ajaxError(null, 'abort', xhr, settings, deferred)
return xhr
} //这个什么东西
if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] //设置同步或者是异步, 然后设置发送的选项
var async = 'async' in settings ? settings.async : true
xhr.open(settings.type, settings.url, async, settings.username, settings.password) for (name in headers) nativeSetHeader.apply(xhr, headers[name]) //设置超时就调用 abord()
if (settings.timeout > 0) abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty
xhr.abort()
ajaxError(null, 'timeout', xhr, settings, deferred)
}, settings.timeout) // avoid sending empty string (#319)
xhr.send(settings.data ? settings.data : null)
return xhr
} //一个适配器接口;
// handle optional data/success arguments
function parseArguments(url, data, success, dataType) {
if ($.isFunction(data)) dataType = success, success = data, data = undefined
if (!$.isFunction(success)) dataType = success, success = undefined
return {
url: url
, data: data
, success: success
, dataType: dataType
}
} $.get = function(/* url, data, success, dataType */){
return $.ajax(parseArguments.apply(null, arguments))
} $.post = function(/* url, data, success, dataType */){
var options = parseArguments.apply(null, arguments)
options.type = 'POST'
return $.ajax(options)
} $.getJSON = function(/* url, data, success */){
var options = parseArguments.apply(null, arguments)
options.dataType = 'json'
return $.ajax(options)
} //还有这种快捷方法啊,没用过呢;
//url这个参数格一个空格后面放 selector 即可把返回的数据里配到 selector的innerHTML取出来;
$.fn.load = function(url, data, success){
if (!this.length) return this
var self = this, parts = url.split(/\s/), selector,
options = parseArguments(url, data, success),
callback = options.success
if (parts.length > 1) options.url = parts[0], selector = parts[1]
options.success = function(response){
self.html(selector ?
$('<div>').html(response.replace(rscript, "")).find(selector)
: response)
callback && callback.apply(self, arguments)
}
$.ajax(options)
return this
} var escape = encodeURIComponent function serialize(params, obj, traditional, scope){
var type, array = $.isArray(obj), hash = $.isPlainObject(obj)
$.each(obj, function(key, value) {
type = $.type(value)
if (scope) key = traditional ? scope :
scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'
// handle data in serializeArray() format
if (!scope && array) params.add(value.name, value.value)
// recurse into nested objects
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
else params.add(key, value)
})
} $.param = function(obj, traditional){
var params = []
params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
serialize(params, obj, traditional)
return params.join('&').replace(/%20/g, '+')
}
})(Zepto) ;(function($){
//对表单进行序列化成数组么么哒;
$.fn.serializeArray = function() {
var result = [], el
$([].slice.call(this.get(0).elements)).each(function(){
el = $(this)
var type = el.attr('type')
if (this.nodeName.toLowerCase() != 'fieldset' &&
!this.disabled && type != 'submit' && type != 'reset' && type != 'button' &&
((type != 'radio' && type != 'checkbox') || this.checked))
result.push({
name: el.attr('name'),
value: el.val()
})
})
return result
} //把serializeArray拼成Get请求的方式;
$.fn.serialize = function(){
var result = []
this.serializeArray().forEach(function(elm){
result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
})
return result.join('&')
} $.fn.submit = function(callback) {
if (callback) this.bind('submit', callback)
else if (this.length) {
var event = $.Event('submit')
this.eq(0).trigger(event)
if (!event.isDefaultPrevented()) this.get(0).submit()
}
return this
} })(Zepto) ;(function($){
// __proto__ doesn't exist on IE<11, so redefine
// the Z function to use object extension instead
if (!('__proto__' in {})) {
//解决IE低版本的——prop——不可以使用的问题;这个会覆盖原来的$.zepto.Z
$.extend($.zepto, {
Z: function(dom, selector){
//dom应该是已经选择的元素的集合(array类型的);
dom = dom || []
//手动复制继承;
$.extend(dom, $.fn)
dom.selector = selector || ''
dom.__Z = true
return dom
},
// this is a kludge but works
isZ: function(object){
return $.type(object) === 'array' && '__Z' in object
}
})
} // getComputedStyle shouldn't freak out when called
// without a valid element as argument
//getComputedStyle还有这个问题..库就是处理兼容的神器啊;
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})(Zepto)
zepto源代码解读的更多相关文章
- linux内核奇遇记之md源代码解读之四
linux内核奇遇记之md源代码解读之四 转载请注明出处:http://blog.csdn.net/liumangxiong 运行阵列意味着阵列经历从无到有,建立了作为一个raid应有的属性(如同步重 ...
- Apache OFbiz entity engine源代码解读
简单介绍 近期一直在看Apache OFbiz entity engine的源代码.为了能够更透彻得理解,也由于之前没有看人别人写过分析它的文章,所以决定自己来写一篇. 首先,我提出一个问题,假设你有 ...
- 分享:json2.js源代码解读笔记
1. 怎样理解"json" 首先应该意识到,json是一种数据转换格式,既然是个"格式",就是个抽象的东西.它不是js对象,也不是字符串,它仅仅是一种格式,一种 ...
- Zepto源代码分析一~核心方法
今天抽出时间复习了一下Zepto的源代码,依照自己的理解进行凝视. 欢迎大家拍砖. 源代码版本号:v1.1.4 源代码下载地址:http://zeptojs.com/ 分析总体代码之后,整理出架构图: ...
- 【Spark】SparkContext源代码解读
SparkContext的初始化 SparkContext是应用启动时创建的Spark上下文对象,是进行Spark应用开发的主要接口,是Spark上层应用与底层实现的中转站(SparkContext负 ...
- Apache Beam WordCount编程实战及源代码解读
概述:Apache Beam WordCount编程实战及源代码解读,并通过intellij IDEA和terminal两种方式调试执行WordCount程序,Apache Beam对大数据的批处理和 ...
- Spark jdbc postgresql数据库连接和写入操作源代码解读
概述:Spark postgresql jdbc 数据库连接和写入操作源代码解读.具体记录了SparkSQL对数据库的操作,通过java程序.在本地开发和执行.总体为,Spark建立数据库连接,读取数 ...
- Zepto源代码分析之二~三个API
因为时间关系:本次仅仅对这三个API($.camelCase.$.contains.$.each)方法进行分析 第一个方法变量转驼峰:$.camelCase('hello-world-welcome' ...
- Redis内存管理的基石zmallc.c源代码解读(一)
当我第一次阅读了这个文件的源代码的时候.我笑了,忽然想起前几周阿里电话二面的时候,问到了自己定义内存管理函数并处理8字节对齐问题. 当时无言以对,在面试官无数次的提示下才答了出来,结果显而易见,挂掉了 ...
随机推荐
- 怎样用好ZBrush中的PaintStop插件
PaintStop是ZBrush®3.1的手绘插件,可以比较真实的模拟手绘风格,尤其是用水彩笔刷画水墨风格画.PaintStop插件可供用户免费使用. PaintStop是一款功能强大的插件,已经被添 ...
- readonly与const
readonly与const 在C#中,readonly 与 const 都是定义常量,但不同之处在于:readonly 是运行时常量,而 const 是编译时常量. ; public void Te ...
- UVALive 6450 Social Advertising DFS解法
题意:一些人有朋友关系,在某个人的社交网站上投放广告可以被所有该人的直接朋友看到,问最小投放多少个广告使给出的人都看到广告.(n<=20) 解法:看到n的范围可以想到用二进制数表示每个人被覆盖与 ...
- Unity使用 UnityVS+VS2013 调试脚本
好消息:UnityVS免费啦 好消息:微软收购了UnityVS公司,UnityVS免费啦 下载地址:https://visualstudiogallery.msdn.microsoft.com/sit ...
- Java基础详解 (一)Java的类成员访问权限修饰词(以及类访问权限)
在一个类的内部,其成员(包括成员变量和成员函数)能否被其他类所访问,取决于该成员的修饰词.Java的类成员访问权限修饰词有四类:private,无(默认情况下),protected和public.其权 ...
- js原生捕鱼达人(二)
昨天写到构造炮弹,有点小bug不知道大家发现没有,今天继续昨天的步骤 7>构造炮弹 思路和前面都是一样一样的 注意构造函数中需要考虑的属性 和 构造函数的原型上面的方法 <sc ...
- swift代理使用
代理声明: //oc调用代理 @objc(NurseListCellDelegate) protocol NurseListCellDelegate : NSObjectProtocol{ func ...
- android实现点击背景图片不同区域实现不同事件
有时候我们拿到一张背景图片,客户要求点击图片的不同区域去跳转或者实现不同的操作事件.我们首先要确认图片的点击区域,往往我们会在布局文件那里下手,但是这样不好做适配,所以我实现了以下方法,基本功能可以实 ...
- Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges. For example, give ...
- C#实现对指定文件夹中文件按修改时间排序
string path = "~/Document/Introduction/团队管理制度/"; DirectoryInfo dirinfo = new Di ...