zepto源碼

/**
*
*    ┏┓   ┏┓
*   ┏┛┻━━━┛┻┓
*   ┃       ┃
*   ┃   ━   ┃
*   ┃ ┳┛ ┗┳ ┃
*   ┃       ┃
*   ┃   ┻   ┃
*   ┃       ┃
*   ┗━┓   ┏━┛Code is far away from bug with the animal protecting
*     ┃   ┃ 神獸保佑,代碼無bug
*     ┃   ┃
*     ┃   ┗━━━┓
*     ┃      ┣┓
*     ┃     ┏┛
*     ┗┓┓┏━┳┓┏┛
*      ┃┫┫ ┃┫┫
*      ┗┻┛ ┗┻┛
*
*/javascript

/* Zepto 1.1.4 - zepto event ajax form ie detect fx fx_methods assets data deferred callbacks selector touch gesture stack ios3 - zeptojs.com/license */
/***
中文註釋由 李祥威 添加,包含了zepto全部17個模塊,爲我的對細節的理解,官方解釋很詳細的地方就不說啦
不免有錯漏,聯繫我: chuangweili@163.com
***/
//把代碼用閉包保護起來,這一塊定義的是zepto對象和他的屬性方法。
//用小括號包住一個匿名函數,返回的就是這個函數,後面跟再跟()就至關於調用這個匿名函數了
var Zepto = (function() {
//定義本對象須要用到的對象,以及緩存快捷方式(優化性能)
var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter,
document = window.document,
//elementDisplay對象用來緩存元素節點默認的display屬性
elementDisplay = {},
//classCache對象用來保存class的名字以及它對應的正則表達式
classCache = {},
//cssNumber對象保存的屬性都是不須要添加px後綴的
cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
//檢測是否爲HTML標籤正則,舉栗子:<div> <h1>
fragmentRE = /^\s*<(\w+|!)[^>]*>/,
//出於優化考慮,匹配只有單一標籤的狀況<div /> <div></div> <div>狀況,裏面不含子元素的
singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
//檢測沒有正確閉合的標籤,舉栗子:<div />
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
//檢測是否是<body><html>根標籤
rootNodeRE = /^(?:body|html)$/i,
//檢測有沒有大寫字母
capitalRE = /([A-Z])/g,css

// 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': document.createElement('tbody'),
'tbody': table, 'thead': table, 'tfoot': table,
'td': tableRow, 'th': tableRow,
'*': document.createElement('div')
},
//元素加載好的的狀態
readyRE = /complete|loaded|interactive/,
//檢測簡單dom選擇器,只能是數字字母組合
simpleSelectorRE = /^[\w-]*$/,
//用來存放每種對象類型,{["object Array"]: array, ["object String"]: string ...},
class2type = {},
//緩存class2type的字符串
toString = class2type.toString,
zepto = {},
camelize, uniq,
//建立臨時div容器
tempParent = document.createElement('div'),
//把下面可能出現的錯誤屬性名稱,替換爲正確的駝峯形式的屬性名稱
propMap = {
'tabindex': 'tabIndex',
'readonly': 'readOnly',
'for': 'htmlFor',
'class': 'className',
'maxlength': 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
'rowspan': 'rowSpan',
'colspan': 'colSpan',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},
//判斷時候是否爲數值,若是有原生isArray方法就用原生的
isArray = Array.isArray ||
function(object){ return object instanceof Array }

//判斷給的元素是否是匹配選擇器,相似原生的matches()方法,這是一個比較新的方法,下面能夠看到,帶前綴
zepto.matches = function(element, selector) {
//任意一個參數爲空或者傳進來的元素不是element類型就退出函數
if (!selector || !element || element.nodeType !== 1) return false
//獲取各內核下的matchesSelector方法,存在的話就用啦
var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
element.oMatchesSelector || element.matchesSelector
if (matchesSelector) return matchesSelector.call(element, selector)
// fall back to performing a selector:
//temp = !parent 有父元素就爲false,沒有結構爲TRUE
var match, parent = element.parentNode, temp = !parent
//沒有父元素就建立一個臨時的父元素,而後把element放裏面
if (temp) (parent = tempParent).appendChild(element)
//在父元素上調用queryselectorall來匹配selector(說就是把parent做爲查詢上下文),在返回的結構中查找是否存在element,若是不存在是會返回-1的,經過位運算~能夠-1轉化爲0,由於這個方法是要返回布爾值
match = ~zepto.qsa(parent, selector).indexOf(element)
//把臨時的父元素div刪除
temp && tempParent.removeChild(element)
return match
}html

//判斷類型,null返回"null",而後再使用對象的toString方法來判斷對象類型,若是class2type沒有對應的,就返回「object」,其餘返回對應的類型值
function type(obj) {
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
}java

//判斷對象類型
function isFunction(value) { return type(value) == "function" }
function isWindow(obj) { return obj != null && obj == obj.window }
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
function isObject(obj) { return type(obj) == "object" }
//是否爲簡單原始對象,例如Object.create(null);就返回false了
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
//判斷是否爲類數組對象 nodeList等
function likeArray(obj) { return typeof obj.length == 'number' }
//壓縮數組,把值爲null和undefined的刪除掉
function compact(array) { return filter.call(array, function(item){ return item != null }) }
//複製數組,concat()方法參數爲空的話,就會返回對當前函數的複製
function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
//把get-name轉化爲駝峯形式getName,(.)表示跟在-後的字符,chr保留着被()匹配內容的引用,把函數賦予變量能夠根據狀況選擇性地賦予須要執行的函數
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
//字符串格式轉化,駝峯轉爲line-height,::轉化爲/
function dasherize(str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase()
}
//去掉數組裏重複的內容,經過判斷indexOf在數組的位置和循環時的索引是否相等
uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
//返回類名對應的正則表達式
function classRE(name) {
return name in classCache ?
classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
}
//判斷是否須要爲該屬性值加"px"後綴
function maybeAddPx(name, value) {
return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
}
//獲取元素節點默認的display類型
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 == "none" && (display = "block")
elementDisplay[nodeName] = display
}
return elementDisplay[nodeName]
}
//獲取子元素集,有原生的children就用,把子元素複製到到數組裏,沒有就用zepto的map方法對當前元素的子元素都進行判斷。 children只返回nodeType爲element的,childNodes會返回全部類型
function children(element) {
return 'children' in element ?
slice.call(element.children) :
$.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
}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, containerjquery

// A special case optimization for a single tag 對於單一元素,沒有子元素什麼的直接建立一個,不用像下面那樣處理
if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))android

if (!dom) {
//若是標籤殘缺就從新生成,像是<div />,RegExp.$1緩存正則中的()內容,就是節點名稱
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
//判斷是否是表單標籤,是的話建立對應表單容器,不是就用div做爲容器了
if (!(name in containers)) name = '*'ios

container = containers[name]
container.innerHTML = '' + html
//這裏把container.childNodes複製給了dom,做爲一個數組返回(數組裏包含dom結構),再把container的子元素一個個刪除
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
}web

if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {
//若是須要設置的屬性是有對應設置方法的話,例如$.width(),那就直接用,沒有的話就用通用的attr()方法
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}ajax

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.
zepto.Z = function(dom, selector) {
dom = dom || []
//讓dom數組繼承$.fn上的全部方法,由於是Dom結構,因此沒有prototype,就只能利用__proto__(是指內部[[prototype]]),ie同窗悲劇了(用ie模塊兼容)
//dom.__proto__ 就是該對象的內部屬性[[prototype]],指向該對象構造函數的prototype
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.init裏至始至終沒有使用new,之因此可以用instanceof來檢測是否爲繼承關係,是由於 dom.__proto__ = $.fn 改變了該對象對構造函數原型的引用(用來記錄誰是它構造函數)
//而zepto.Z.prototype = $.fn 改變了zepto.Z的原型
//一個對象的__proto__ 等於 一個函數的prototype時,爲繼承關係
//例如 var a = function(){}; a.prototype = window; b = {}; b.__proto__ = window; b instanceof a; 會返回TRUE
return object instanceof zepto.Z
}

// `$.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) { //建立zepto集合,選擇對應的節點
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)
}

// `$` 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) //$("a:alilink", $("body"))其實就是zepto.init("a:alilink", $("body"))
}

//把source上的數據拓展到target上
function extend(target, source, deep) {
for (key in source)
//查看是否須要深度拓展,深度拓展徹底產生新對象,所以改變source就不會改變target的了
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
//若是source的key是對象,而target對應key不是,那就給他建立新對象
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
//同理,數組也同樣
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
//深度拓展的話繼續看當前key下是否有東西,有就繼續拓展下去
extend(target[key], source[key], deep)
}
//把每一個key的值複製過去,非深度拓展只複製對象的基本類型,對象仍屬於原來的引用。 這裏沒有判斷所以source上的屬性會覆蓋掉target上的。
else if (source[key] !== undefined) target[key] = source[key]
}

// Copy all but undefined properties from one or more
// objects to the `target` object.
$.extend = function(target){
var deep, args = slice.call(arguments, 1) //arguments包含了全部實參,從第二個開始複製
if (typeof target == 'boolean') { //傳進來的第一個參數決定是否是要深度拓展
deep = target
target = args.shift() //把target對象從參數數組拿出來,給到target,剩下的就做爲source對象了
}
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,
//從第一個字符判斷是否選擇id 類
maybeID = selector[0] == '#',
maybeClass = !maybeID && selector[0] == '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
isSimple = simpleSelectorRE.test(nameOnly)
return (isDocument(element) && isSimple && maybeID) ?
//若是element是document,是簡單選擇器,可能爲id的狀況,直接查id,沒有找到返回空數組
( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
//判斷element是否是節點元素或者document,都不是返回空數組
(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
)
}

//從nodes集合中過濾,只包含匹配selector的集合
function filtered(nodes, selector) {
return selector == null ? $(nodes) : $(nodes).filter(selector)
}

//查看瀏覽器有沒有原生的contain方法
$.contains = document.documentElement.contains ?
function(parent, node) {
//有原生contains方法的話,若是二者不相等,而且包含就返回TRUE
return parent !== node && parent.contains(node)
} :
//沒有原生方法的話,循環判斷node的父元素是否等於parent,一直到最頂部 null 才停
function(parent, node) {
while (node && (node = node.parentNode))
if (node === parent) return true
return false
}

//判斷arg是否爲函數,是的話做爲函數調用(payload能夠攜帶相關的信息數據),不是則做爲值
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}

//設置value爲null,或者undefined的話,就執行刪除屬性操做,有值的話就設置屬性值
function setAttribute(node, name, value) {
value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
}

// 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 :
//判斷是否是JSON對象,\[是判斷是否以[開頭是對於[{a: 1,b: 2}]數組裏放對象狀況
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value )
: value
} catch(e) {
return value
}
}

//把方法拓展到zepto對象上去
$.type = type
$.isFunction = isFunction
$.isWindow = isWindow
$.isArray = isArray
$.isPlainObject = isPlainObject

$.isEmptyObject = function(obj) {
var name
//判斷有沒有屬性在裏面,哪怕一個就返回false了,爲空對象
for (name in obj) return false
return true
}

$.inArray = function(elem, array, i){
//判斷elem是否在數組裏,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 = { }

//遍歷elements,把每一個element放到callback處理
$.map = function(elements, callback){
var value, values = [], i, key
//若是是數組或者nodeList,遍歷它們,執行結果爲null和undefined會被過濾掉
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++)
//和上面map的區別是,這裏將每一個元素做爲上下文來運行callback,而且把索引和對應值傳進去,返回false會退出循環
if (callback.call(elements[i], i, elements[i]) === false) return elements
} else {
for (key in elements)
if (callback.call(elements[key], key, elements[key]) === false) return elements
}

return elements
}

//暴露過濾方法,返回在callback執行結果爲TRUE的元素組成的新數組
$.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
//給zepto對象拓展各類方法
$.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
//在zepto的Dom方法裏也搞一份map
map: function(fn){
return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
},
//複製集合,返回一個zepto對象
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
if (readyRE.test(document.readyState) && document.body) callback($)
//DOMContentLoaded事件當Dom加載完成就觸發,不須要等待圖片,腳本等加載完成,在load以前觸發,load須要等待頁面徹底加載完
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() },
//獲取當前集合的長度
size: function(){
return this.length
},
remove: function(){
//將當前集合每一個元素從Dom刪除,判斷是否存在父節點,再調用原生removeChild()方法,若是是document的話直接把document對象放數組返回
return this.each(function(){
if (this.parentNode != null)
this.parentNode.removeChild(this)
})
},
each: function(callback){
//every方法測試當前集合是否都經過callback測試,都經過返回TRUE。
emptyArray.every.call(this, function(el, idx){
//若是執行過程當中有callback顯式返回false(不包括0 null undefined),會退出循環
return callback.call(el, idx, el) !== false
})
return this
},
//過濾當前集合,返回結果爲TRUE的
filter: function(selector){
//若是selector是函數的話,第一次執行this.not(selector)返回函數運行結果爲falsy(0,false,null,undefined)的集合,第二次調用this.not(this.not(selector))至關於不要第一次返回的集合,要剩下的那些。
if (isFunction(selector)) return this.not(this.not(selector))
return $(filter.call(this, function(element){
return zepto.matches(element, selector)
}))
},
//把selector選擇到的元素追加到當前集合,會去掉重複的
add: function(selector,context){
return $(uniq(this.concat($(selector,context))))
},
//判斷當前集合中的第一個元素this[0]是否匹配selector
is: function(selector){
return this.length > 0 && zepto.matches(this[0], selector)
},
//從當前集合篩選出不在選中範圍內的集合
not: function(selector){
var nodes=[]
//若是selector爲函數而且能夠經過call存在的話,把執行結果爲false的添加到nodes裏
if (isFunction(selector) && selector.call !== undefined)
this.each(function(idx){
if (!selector.call(this,idx)) nodes.push(this)
})
else {
//excludes 表示的是被selector選中的集合,若是是字符串的話,直接filter過濾出來
var excludes = typeof selector == 'string' ? this.filter(selector) :
//若是是nodeList的話,直接複製當前nodeList,item方法只有函數上纔有,數組沒有,用來排除selector爲數組狀況。以上狀況都不是那就做爲選擇器使用
(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
this.forEach(function(el){
//遍歷集合,若是沒有出如今excludes裏,就表示該元素沒有沒選中,添加到nodes數組中,最後返回nodes集合
if (excludes.indexOf(el) < 0) nodes.push(el)
})
}
return $(nodes)
},
//過濾當前集合,篩選出包含selector的集合
has: function(selector){
return this.filter(function(){
return isObject(selector) ?
//若是selector是對象(node)的話,就使用contain查找當前集合是否包含selector
$.contains(this, selector) :
//若是不是對象,就是用find查找selector
$(this).find(selector).size()
})
},
//這裏把-1單獨判斷是由於slice(-1)能夠取最後一個,不須要第二個參數end。而 + idx + 1 是由於倒數取值狀況slice(-3,-2), + -3 + 1 = -2,這裏的第一個加號是用來轉化爲數字類型,避免用戶eq("1")
eq: function(idx){
return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
},
//獲取第一個集合,判斷el是否爲zepto對象(isObject若是是zepto對象會返回false),是的話直接返回,不是弄成zepto對象再返回
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)
},
//查找匹配selector的元素
find: function(selector){
var result, $this = this
//若是selector不存在,返回空數組
if (!selector) result = []
//若是selector爲對象(Dom或者zepto對象),遍歷selector,在當前集合($this)上查看是否包含任意selector,有的話就會返回TRUE,並記錄該selector到result裏面
else if (typeof selector == 'object')
result = $(selector).filter(function(){
var node = this
//some回調第一個參數指向當前對象,所以爲parent,若是裏面$.contains(parent, node)返回TRUE,那麼some也會返回TRUE
return emptyArray.some.call($this, function(parent){
return $.contains(parent, node)
})
})
//若是當前集合只有一個子集,那麼直接就在這個子集上查找selector
else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
//若是當前集合有多個子集,則使用map遍歷
else result = this.map(function(){ return zepto.qsa(this, selector) })
return result
},
//查找第一個匹配到的父級元素
closest: function(selector, context){
var node = this[0], collection = false
//若是是元素節點或者zepto集合,那麼轉化爲zepto對象而且放到collection
if (typeof selector == 'object') collection = $(selector)
//node存在,判斷collection是否爲false,若是node不在collection集合裏,或者node裏沒有匹配的selector,進行下一步判斷,若是前面判斷失敗,表示查找完成,返回$(node)
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
//node不等於給定的上下文環境,而且node不爲document,而且node.parentNode存在的話,把node.parentNode 賦給node,一層一層把父元素拿去判斷。若是context和node相等的話返回這個node
node = node !== context && !isDocument(node) && node.parentNode
return $(node)
},
//返回全部父元素,若是提供了selector,返回匹配的全部父元素
parents: function(selector){
var ancestors = [], nodes = this
//一直循環到最頂層,它的長度爲0,中止
while (nodes.length > 0)
//遍歷全部父級,若是父級還有父元素,而且不是document,沒有和ancestors裏重複,就把nodes指向上一級,繼續遍歷
nodes = $.map(nodes, function(node){
if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
ancestors.push(node)
return node
}
})
//若是提供了selector的,過濾出符合條件的
return filtered(ancestors, selector)
},
//獲取直接父元素,經過plunk遍歷集合獲取父元素節點
parent: function(selector){
return filtered(uniq(this.pluck('parentNode')), selector)
},
//獲取當前集合的直接子元素們
children: function(selector){
return filtered(this.map(function(){ return children(this) }), selector)
},
//獲取當前集合的子節點,childNodes是會返回text節點和註釋節點的,children屬性則不返回
contents: function() {
return this.map(function() { return slice.call(this.childNodes) })
},

siblings: function(selector){
//這一層過濾是若是提供了selector,只返回符合條件的sibling
return filtered(this.map(function(i, el){
//這一層過濾是經過children(el.parentNode)獲取全部子元素,而後剔除掉當前那個
return filter.call(children(el.parentNode), function(child){ return child!==el })
}), selector)
},
//經過把innerHTML設置爲空清除掉當前節點下的Dom
empty: function(){
return this.each(function(){ this.innerHTML = '' })
},
// `pluck` is borrowed from Prototype.js
pluck: function(property){
//遍歷當前集合獲取屬性值
return $.map(this, function(el){ return el[property] })
},
show: function(){
return this.each(function(){
//把當前集合的每一個元素做爲上下文,去判斷display屬性,被內聯樣式設置爲none的話恢復顯示
this.style.display == "none" && (this.style.display = '')
//若是被CSS樣式設置爲none的,經過內聯樣式設置回默認值
if (getComputedStyle(this, '').getPropertyValue("display") == "none")
this.style.display = defaultDisplay(this.nodeName)
})
},
//經過before方法把新內容添加到當前集合元素前,而後把當前的移除掉
replaceWith: function(newContent){
return this.before(newContent).remove()
},
//把當前集合中的每一個元素用structure包裹起來
wrap: function(structure){
var func = isFunction(structure)
//若是當前集合有子元素且沒有傳函數進來的話,緩存structure,注意get(0)返回的是原生的Dom
if (this[0] && !func)
var dom = $(structure).get(0),
clone = dom.parentNode || this.length > 1
//以當前集合中的每一個子集爲上下文調用wrapAll(),若是傳進來的structure是函數,那麼就調用這個函數,使用它返回的結構做爲structure。若是不是判斷clone
//clone存在表示傳進來的structure可能爲當前頁面的dom,或者須要wrap的元素超過一個,所以須要深度克隆dom做爲wrapAll的structure,不然就是用dom
return this.each(function(index){
$(this).wrapAll(
func ? structure.call(this, index) :
clone ? dom.cloneNode(true) : dom
)
})
},
//把當前集合所有放到一個結構裏
wrapAll: function(structure){
if (this[0]) {
//把structure轉爲zepto後插入到第一個匹配到的子集前面,而後把structure覆蓋爲最裏面的元素,再把this把當前集合所有移進到最裏面
$(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
},
//把當前集合的內容(不包含Dom結構)放到structure裏
wrapInner: function(structure){
var func = isFunction(structure)
return this.each(function(index){
//使用contents()只獲取每一個元素裏的內容,若是內容存在就把內容依次放到dom裏,沒內容的話就把dom移進去。
//由於每一次dom都會被移動,也就是先把structure移到第一個匹配到的子集裏,而後移動第二個,第三個,所以最後的位置就在最後一個匹配到的子集元素裏
var self = $(this), contents = self.contents(),
dom = func ? structure.call(this, index) : structure
contents.length ? contents.wrapAll(dom) : self.append(dom)
})
},
//把直接父元素滅了,原理就是用當前集合的children做爲新內容替換掉本身
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則判斷當前是否隱藏,用來下一步控制顯隱
//若是不是undefined,則判斷setting的真假值,進而判斷顯隱性。
;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
})
},
//調用原生的屬性方法previousElementSibling,nextElementSibling,再過濾出匹配的
prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
html: function(html){
//0 in argument判斷是否傳入了參數,若是傳入了的話,把本來的HTML結構清空,若是傳進來的HTML結構,那麼就用它替代舊的,若是是對原來結構的調整函數,那就調用這個函數
return 0 in arguments ?
this.each(function(idx){
var originHtml = this.innerHTML
$(this).empty().append( funcArg(this, html, idx, originHtml) )
}) :
//沒有傳進參數的話,就看當前集合有沒有東西,有的化返回第一個子元素的結構,沒有的話返回null
(0 in this ? this[0].innerHTML : null)
},
text: function(text){
return 0 in arguments ?
this.each(function(idx){
//這裏和html方法不一樣之處在於保存funcArg的結果做爲新的內容,''+newText用來轉化爲字符串
var newText = funcArg(this, text, idx, this.textContent)
this.textContent = newText == null ? '' : ''+newText
}) :
(0 in this ? this[0].textContent : null)
},
//讀取或設置Dom 的attitude
attr: function(name, value){
var result
return (typeof name == 'string' && !(1 in arguments)) ?
//若是name爲字符串而且只傳了一個參數的話,表示讀取attribute的值,那麼判斷當前集合是否是是否存在子集,若是不存在或者第一個子集不是元素類型的話,返回undefined
(!this.length || this[0].nodeType !== 1 ? undefined :
//若是getAttribute獲取返回null,可是name的確在這個元素上,那麼表示這個attribute是直接定義上去的,例如element.num = 1 ,須要經過this[0][name]來取值
(!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
) :
//這裏是進行attribute設置操做
this.each(function(idx){
if (this.nodeType !== 1) return
//若是傳進來的是對象,那麼就遍歷該對象,把屬性設置到當前集合每一個元素上
if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
//最後一種狀況是處理第二個傳入的參數,在當前元素上調用該方法把返回結果做爲name的值
else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
})
},
removeAttr: function(name){
//原理就是使用上面提到的setAttribute,當沒有傳入值的時候爲移除屬性
return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) })
},
prop: function(name, value){
//修正有可能寫錯的屬性名
name = propMap[name] || name
//判斷有沒有傳入value
return (1 in arguments) ?
this.each(function(idx){
//傳了value表示設置操做,調用funcArg,把結果做爲該屬性值
this[name] = funcArg(this, value, idx, this[name])
}) :
//沒有傳入第二個參數表示進行讀取操做
(this[0] && this[0][name])
},
//讀取或者設置帶有data-前綴的attribute
data: function(name, value){
//把那麼轉化爲-xx-xx的小寫模式,可是這裏的'data-'後面多了一行,變成data--mime了
//若是你使用的是包含了data模塊的zepto,那麼這個方法就被覆蓋了,那就不是簡單滴存儲到元素上了
//data模塊支持存儲任意對象
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)
}) :
//沒有給值的話也是返回第一個元素的值,須要判斷是否是多選的,若是是就把選擇的值放在數組裏返回
(this[0] && (this[0].multiple ?
$(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
this[0].value)
)
},
//獲取元素相對於document的位置
offset: function(coordinates){
//若是提供了上,左位置,就會設置該位置
if (coordinates) return this.each(function(index){
var $this = $(this),
coords = funcArg(this, coordinates, index, $this.offset()),
//parentOffset爲當前元素第一個position爲「relative」, 「absolute」或「fixed」的元素,由於經常使用這些來限制子元素爲absolute的活動範圍
parentOffset = $this.offsetParent().offset(),
props = {
top: coords.top - parentOffset.top,
left: coords.left - parentOffset.left
}
//若是是static,設置爲relative來移動,不影響其餘元素
if ($this.css('position') == 'static') props['position'] = 'relative'
$this.css(props)
})
if (!this.length) return null
//getBoundingClientRect返回一個對象,其中包含了left、right、top、bottom四個屬性,分別對應了該元素的左上角和右下角相對於瀏覽器窗口(viewport)左上角的距離
var obj = this[0].getBoundingClientRect()
return {
//left和top加上滾動了的距離
left: obj.left + window.pageXOffset,
top: obj.top + window.pageYOffset,
width: Math.round(obj.width),
height: Math.round(obj.height)
}
},
css: function(property, value){
//若是隻傳入property的狀況
if (arguments.length < 2) {
var element = this[0], computedStyle = getComputedStyle(element, '')
if(!element) return
//若是property爲字符串,那麼先看內聯樣式有沒有,這裏要使用駝峯形式。沒有則獲取最終應用到元素上的樣式,這裏不用駝峯
if (typeof property == 'string')
return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
//傳入property數組的話,返回一個props對象,把每一個屬性查詢結果存放在裏面
else if (isArray(property)) {
var props = {}
$.each(property, function(_, prop){
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
})
return props
}
}

var css = ''
if (type(property) == 'string') {
//若是value爲falsy值,那麼就從style裏刪除掉這個樣式,removeProperty不能用駝峯形式
if (!value && value !== 0)
this.each(function(){ this.style.removeProperty(dasherize(property)) })
else
//不是刪除的話,就轉化爲樣式寫法,background-color: red; 要添加px後綴的就添加上
css = dasherize(property) + ":" + maybeAddPx(property, value)
} else {
//若是property是對象的話,遍歷它,若是值爲falsy切不爲0的話,就去掉,否者也轉化成樣式
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]) + ';'
}
//一次性把CSS樣式添加到各元素style裏,注意是+=不是=,否則會覆蓋掉原有的
return this.each(function(){ this.style.cssText += ';' + css })
},
index: function(element){
//獲取元素位置,若是有element的話,返回第一個element在當前集合位置,沒有的話返回當前集合第一個元素相對於兄弟姐妹的位置
return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
},
hasClass: function(name){
if (!name) return false
return emptyArray.some.call(this, function(el){
//這裏的this是classRE(name)生成的對應類名正則,由於some方法第二個參數能夠指定callback的this。
//集合中只要有一個含有該類就返回TRUE
return this.test(className(el))
}, classRE(name))
},
addClass: function(name){
if (!name) return this
return this.each(function(idx){
if (!('className' in this)) return
classList = []
var cls = className(this), newName = funcArg(this, name, idx, cls)
//把要添加的類逐個進行判斷,看原來有沒有,沒有才添加到classList數組
newName.split(/\s+/g).forEach(function(klass){
if (!$(this).hasClass(klass)) classList.push(klass)
}, this)
//添加新類的時候判斷原來有沒有類,有的話用空格分開,classList數組轉化爲用空格分開的字符串
classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
})
},
removeClass: function(name){
return this.each(function(idx){
if (!('className' in this)) return
if (name === undefined) return className(this, '')
classList = className(this)
funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
//經過replace把匹配到的類名替換爲空,後面再把多餘的空格去掉
classList = classList.replace(classRE(klass), " ")
})
className(this, classList.trim())
})
},
toggleClass: function(name, when){
if (!name) return this
return this.each(function(idx){
var $this = $(this), names = funcArg(this, name, idx, className(this))
names.split(/\s+/g).forEach(function(klass){
//若是提供了when的話,當它的值爲真才添加類,不然移除。若是when爲undefined,那麼就看目前有沒有這個類,有就移除,沒有就添加
(when === undefined ? !$this.hasClass(klass) : when) ?
$this.addClass(klass) : $this.removeClass(klass)
})
})
},
//判斷向下滾動了多少
scrollTop: function(value){
if (!this.length) return
//判斷有沒有原生的scrollTop屬性
var hasScrollTop = 'scrollTop' in this[0]
//沒有傳入value的話表示讀取,返回scrollTop(body的狀況),沒有的話返回pageYOffset(window)
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
//一樣若是是設置位置的話,支持scrollTop的用它,不支持的話使用window的scrollTo方法
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) })
},
//獲取相對於非static祖先元素的位置
position: function() {
if (!this.length) return
//獲取當前集合第一個元素
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
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
offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
offset.left -= parseFloat( $(elem).css('margin-left') ) || 0

// Add offsetParent borders
//由於如今的top和left是相對左上角,所以要減掉邊距
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 {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
}
},
offsetParent: function() {
return this.map(function(){
//獲取每一個元素的offsetParent,沒有的話表示爲document.body,由於body的offsetParent爲null
var parent = this.offsetParent || document.body
//若是不爲根節點,而且它的佈局方式是默認的static,那麼就用它的offsetParent覆蓋當前parent,繼續向上判斷,直到非static的祖先
while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
parent = parent.offsetParent
return parent
})
}
}

// for now
$.fn.detach = $.fn.remove

// Generate the `width` and `height` functions
;['width', 'height'].forEach(function(dimension){
//把首字母進行大寫
var dimensionProperty =
dimension.replace(/./, function(m){ return m[0].toUpperCase() })
//把width,height方法拓展到$.fn裏
$.fn[dimension] = function(value){
var offset, el = this[0]
// 沒有傳入值表示查詢,若是是window對象,返回innerWidth(Height)的值,瀏覽器窗口顯示高寬
if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
//若是是document,返回scrollWidth(Height),當前文檔的高寬
isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
//其餘元素調用offset方法取值
(offset = this.offset()) && offset[dimension]
//傳入值的話把當前集合每一個元素都用css方法設置寬高
else return this.each(function(idx){
el = $(this)
el.css(dimension, funcArg(this, value, idx, el[dimension]()))
})
}
})

function traverseNode(node, fun) {
//先對node自己操做一遍,判斷是否是script標籤,有的話須要執行裏面的腳本
fun(node)
//再遍歷後代節點,看裏面有沒script標籤,整個node檢查一遍
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.forEach(function(operator, operatorIndex) {
//adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], prepend, append求餘結果爲0
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)
//對參數進行判斷,若是是HTML字符串,標籤名就先轉化爲Dom結構
return argType == "object" || argType == "array" || arg == null ?
arg : zepto.fragment(arg)
}),
//copyByClone判斷當前集合在頁面上是否爲多個,多個的話nodes不能直接移動,要克隆,才能給集合中每一個元素都進行操做
parent, copyByClone = this.length > 1
//若是沒有傳參數,返回當前對象
if (nodes.length < 1) return this
//_是各元素在當前集合索引,target是各元素對象
return this.each(function(_, target){
//prepend, append爲1,after,before爲0,append和append用本身做爲父元素,經過覆蓋target爲子元素來實現insertBefore
parent = inside ? target : target.parentNode

// convert all methods to a "before" operation
target = operatorIndex == 0 ? target.nextSibling : //0是after操做,insertBefore方法的話就是插入到目標元素的相鄰下一個元素的前面
operatorIndex == 1 ? target.firstChild : //1是prepend操做,insertBefore方法的話就是插入到目標元素所在集合的第一個元素前面
operatorIndex == 2 ? target :
null //append操做,insertBefore方法第二個參數爲null的話,默認插到當前集合最後一個

var parentInDocument = $.contains(document.documentElement, parent)

nodes.forEach(function(node){
//若是是要對多個元素進行操做append等操做
if (copyByClone) node = node.cloneNode(true)
//若是當前元素沒有parent的話,就退出而且刪除該元素,執行不了insertBefore方法
else if (!parent) return $(node).remove()

//到這裏就進行插入操做
parent.insertBefore(node, target)
//若是是在script裏面插入內容,那麼要以window爲上下文執行裏面的內容
if (parentInDocument) traverseNode(node, function(el){
if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
(!el.type || el.type === 'text/javascript') && !el.src)
window['eval'].call(window, el.innerHTML)
})
})
})
}

// after => insertAfter
// prepend => prependTo
// before => insertBefore
// append => appendTo
$.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
//在裏面反向調用上面的方法,把傳入的HTML做爲當前集合,把當前集合做爲傳入的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

return $
})()

//把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' },
//handles的大概結構:
//handles = {
// 元素的zid:[handler對象1,handler對象2 ...]
//}
handlers = {},
specialEvents={},
focusinSupported = 'onfocusin' in window,
//不支持冒泡的事件
focus = { focus: 'focusin', blur: 'focusout' },
hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }

specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'

//獲取/賦予元素一個標示符
function zid(element) {
return element._zid || (element._zid = _zid++)
}

//查找元素的事件處理函數
function findHandlers(element, event, fn, selector) {
event = parse(event)
if (event.ns) var matcher = matcherFor(event.ns)
return (handlers[zid(element)] || []).filter(function(handler) {
return handler
//若是event.e不爲falsy值,判斷當前處理函數的事件類型是否等於傳入的事件類型,其實就是想執行後面的判斷
&& (!event.e || handler.e == event.e)
//判斷時間的命名空間時候相同
&& (!event.ns || matcher.test(handler.ns))
//判斷fn是否指向同一個,由於函數是引用類型,你在上面加點東西,其餘對該函數的引用也能看到
&& (!fn || zid(handler.fn) === zid(fn))
//判斷選擇器是否相同
&& (!selector || handler.sel == selector)
})
}

//解析事件爲數組
function parse(event) {
//先轉化爲字符串再切割爲數組
var parts = ('' + event).split('.')
//返回一個對象,包含事件類型,命名空間
return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}

//生成命名空間的正則
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}

//設置捕獲階段,若是是focus和blur事件,則設爲捕獲階段,來達到冒泡的目的
function eventCapture(handler, captureSetting) {
return handler.del &&
(!focusinSupported && (handler.e in focus)) ||
!!captureSetting
}

//不支持mouseenter和mouseleave的話,就用mouseover和mouseout來替代
//若是支持focusin事件的話,就用focusin和focusout替代focus和blur
function realEvent(type) {
return hover[type] || (focusinSupported && focus[type]) || type
}

//處理事件監聽
function add(element, events, fn, data, selector, delegator, capture){
var id = zid(element), set = (handlers[id] || (handlers[id] = []))
//同時添加多個事件支持,空格切割爲數組
events.split(/\s/).forEach(function(event){
//若是是ready事件,就添加到document上
if (event == 'ready') return $(document).ready(fn)
var handler = parse(event)
//把數據保存到該handler上去
handler.fn = fn
//selector 能夠選擇是否是隻執行一次事件處理函數
handler.sel = selector
// emulate mouseenter, mouseleave
if (handler.e in hover) fn = function(e){
//relatedTarget 是指相對於觸發事件元素的另外一個元素,由於鼠標無非從一個元素移動到另外一個元素上,mouseover和mouseout纔有這個事件屬性,所以mouseenter, mouseleave須要模仿
var related = e.relatedTarget
//第一種狀況!related表示爲mouseenter, mouseleave事件,執行事件處理函數
//第二種狀況若是related有值,而且不是元素本身,也不是觸發元素的子節點,那也執行事件處理
if (!related || (related !== this && !$.contains(this, related)))
return handler.fn.apply(this, arguments)
}
handler.del = delegator
var callback = delegator || fn
handler.proxy = function(e){
e = compatible(e)
//判斷有沒有調用過stopImmediatePropagation方法,若是一個元素對一個事件添加多個事件監聽,那麼stopImmediatePropagation能夠禁止剩下那些事件處理函數調用
//而且也不會冒泡了,代理不了,因此返回
if (e.isImmediatePropagationStopped()) return
//把當前的事件對象信息保存到e上去,由於這些事件對象也是引用的,例如 MouseEvent
e.data = data
var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
//若是事件處理函數返回false的時候,阻止默認行爲和冒泡
if (result === false) e.preventDefault(), e.stopPropagation()
return result
}
//設置這個handler是第幾個,由於length是以前set的長度,恰好就等於這個handler加入set以後的索引 B)
handler.i = set.length
//把當前handler記錄到handlers上去
set.push(handler)
if ('addEventListener' in element)
element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
}

//刪除掉綁定了的事件監聽函數
function remove(element, events, fn, selector, capture){
var id = zid(element)
;(events || '').split(/\s/).forEach(function(event){
//遍歷該元素的handlers,找到符合條件的handler
findHandlers(element, event, fn, selector).forEach(function(handler){
//從事件監聽數組中刪除掉匹配的handler,注意的是這樣刪除不會影響數組的長度,例如 [1,2,3],刪除第一個變爲[undefined,2,3] 這樣才能保證handler.i正確性
delete handlers[id][handler.i]
//最後刪除掉事件監聽
if ('removeEventListener' in element)
element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
})
}

//把上面的兩函數拓展到zepto的event對象上
$.event = { add: add, remove: remove }

//讓context對象代理fn裏面的this,沒有代理的話this是指向觸發事件的元素的
$.proxy = function(fn, context) {
//把除了前兩個參數fn和context的保存爲參數
var args = (2 in arguments) && slice.call(arguments, 2)
if (isFunction(fn)) {
//若是傳入的第一個參數是函數的話,就返回一個新的函數,把context做爲上下文來調用fn
var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) }
//proxyFn是返回執行fn的,因此id應該保持一致
proxyFn._zid = zid(fn)
return proxyFn
} else if (isString(context)) {
if (args) {
//若是傳入的第二個參數是字符串而且還有第三個以上參數的話,把fn[context], fn按順序插到args數組開頭
args.unshift(fn[context], fn)
//調用$.proxy,參數爲(fn[context], fn, 第三個參數, ...)
//也就是說穿進來的fn爲對象,context爲該對象上的屬性,屬性值纔是函數
return $.proxy.apply(null, args)
} else {
//沒有附加參數的話,直接傳入正確的函數和上下文對象
return $.proxy(fn[context], fn)
}
} else {
//沒有傳入參數報錯
throw new TypeError("expected function")
}
}

//bind和unbind都是棄用的接口,這裏是爲了兼容之前基於老版本zepto寫的的程序不出錯
$.fn.bind = function(event, data, callback){
return this.on(event, data, callback)
}
$.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',
//有些瀏覽器沒有原生的isImmediatePropagationStopped方法,例如低版本Android
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
}

//事件對象兼容處理
function compatible(event, source) {
if (source || !event.isDefaultPrevented) {
source || (source = event)

$.each(eventMethods, function(name, predicate) {
var sourceMethod = source[name]
event[name] = function(){
//調用preventDefault,stopImmediatePropagation,stopPropagation,而後把對應的isDefaultPrevented,isImmediatePropagationStopped,isPropagationStopped返回值爲TRUE
this[predicate] = returnTrue
return sourceMethod && sourceMethod.apply(source, arguments)
}
event[predicate] = returnFalse
})
//查看有沒有defaultPrevented,沒有的話判斷returnValue的值,returnValue也沒有就只能用嘗試用廢棄的方法getPreventDefault(),任意一個返回TRUE,就把事件的isDefaultPrevented設爲TRUE
//由於有些瀏覽器沒有defaultPrevented屬性
if (source.defaultPrevented !== undefined ? source.defaultPrevented :
'returnValue' in source ? source.returnValue === false :
source.getPreventDefault && source.getPreventDefault())
//由於isDefaultPrevented是方法,所以也應該指向一個方法
event.isDefaultPrevented = returnTrue
}
return event
}

//建立代理事件
function createProxy(event) {
//把源事件保存起來
var key, proxy = { originalEvent: event }
for (key in event)
//過濾掉忽略的和值爲undefined的屬性,把須要的屬性添加到代理上去
if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]

return compatible(proxy, event)
}

//delegate,undelegate,live,die方法都是廢棄的,保留下來兼容之前程序
$.fn.delegate = function(selector, event, callback){
return this.on(event, selector, callback)
}
$.fn.undelegate = function(selector, event, callback){
return this.off(event, selector, callback)
}

$.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
//若是傳進來的event是一個事件對象{click:"click",mouseover:"mouseover"},或者函數的話調用each遍歷
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.on(type, selector, data, fn, one)
})
return $this
}
//selector傳的是undefined,null之類的無效值狀況,從新賦值
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = data, data = selector, selector = undefined
//data爲函數,或者傳了false值的話,callback和data從新賦值
if (isFunction(data) || data === false)
callback = data, data = undefined

if (callback === false) callback = returnFalse

return $this.each(function(_, element){
//若是是但願只調用一次事件處理函數的話,生成autoRemove函數,先刪除掉事件監聽,而後在當前元素上執行事件處理
if (one) autoRemove = function(e){
remove(element, e.type, callback)
//把以當前對象爲執行上下文的事件處理結果返回給autoRemove
return callback.apply(this, arguments)
}
//若是selector存在的話,建立事件委託
if (selector) delegator = function(e){
//match是指,在觸發事件元素上找到的第一個匹配selector的祖先元素,而後在這個對象上調用事件處理函數
var evt, match = $(e.target).closest(selector, element).get(0)
//若是找到的元素不等於添加事件監聽的元素自己,進行事件委託
if (match && match !== element) {
//把找到元素和當前事件監聽的元素都記錄到委託事件對象上,返回委託事件對象
evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
//把以match爲執行上下文的事件處理函數處理結果返回給delegator
return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
}
}
//添加事件監聽,on對參數進行預處理,add除了監聽事件,還須要把事件信息記錄到handlers對象
add(element, event, callback, data, selector, delegator || autoRemove)
})
}

//分離掉用on添加的事件處理,callback必須是和添加時的一致,匿名函數取消不了,壓根就是不一樣對象
$.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)
})
}

//一般事件時交互觸發的,但也能夠主動觸發事件,這個方法是會冒泡的,下面的triggerHandler不會
$.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){
e = createProxy(isString(event) ? $.Event(event) : event)
e._args = args
e.target = element
//原理是到handlers對象上找該元素對象事件下的事件處理函數,而後執行他們,沒有真正意義上的產生事件
$.each(findHandlers(element, event.type || event), function(i, handler){
result = handler.proxy(e)
if (e.isImmediatePropagationStopped()) return false
})
})
return result
}

// 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)
//若是沒有穿callback的話,默認表單元素的話會有focus和blur方法,其餘元素focus不了
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])
//初始化事件對象,type爲事件類型,如click,bubbles爲是否冒泡,第三個參數表示是否能夠用preventDefault方法來取消默認操做
event.initEvent(type, bubbles, true)
return compatible(event)
}
//把zepto對象傳進去
})(Zepto)


//接下來爲Ajax部分
;(function($){
var jsonpID = 0,
document = window.document,
key,
name,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
scriptTypeRE = /^(?:text|application)\/javascript/i,
xmlTypeRE = /^(?:text|application)\/xml/i,
jsonType = 'application/json',
htmlType = 'text/html',
blankRE = /^\s*$/

// trigger a custom event and return false if it was cancelled
//用來定製而且觸發Ajax相關的事件,這樣用戶就能夠在不一樣階段添加對應的操做
function triggerAndReturn(context, eventName, data) {
var event = $.Event(eventName)
$(context).trigger(event, data)
return !event.isDefaultPrevented()
}

// trigger an Ajax "global" event
//setting是用戶調用$.ajax(setting)傳進來的對象,上面包含了用戶需定義的Ajax屬性和不一樣階段須要執行的操做(事件回調)
function triggerGlobal(settings, context, eventName, data) {
if (settings.global) return triggerAndReturn(context || document, eventName, data)
}

// Number of active Ajax requests
$.active = 0

//下面這個幾個函數看名字就是會在Ajax請求的不一樣階段被調用,而後這些函數會產生和觸發對應事件,執行用戶定義的操做
function ajaxStart(settings) {
//若是global爲true,而且active爲0,active++是判斷再加一,因此能夠判斷是否是最開始
//而後生成並執行ajaxStart事件上的回調函數
if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}

//--$.active 先減一,再判斷是否爲0,爲0纔會觸發ajaxStop
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
//若是用戶的beforeSend事件處理函數返回false,或者triggerGlobal返回false,能夠取消這個Ajax請求
if (settings.beforeSend.call(context, xhr, settings) === false ||
triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
return false
//能執行到這裏說明ajaxBeforeSend執行沒問題,因此觸發ajaxSend
triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}

function ajaxSuccess(data, xhr, settings, deferred) {
//context用戶定義的執行回調函數的上下文對象
var context = settings.context, status = 'success'
//調用成功後須要執行的函數
settings.success.call(context, data, status, xhr)
//若是加載了callbacks和deferred模塊的話,觸發deferred對象的resolveWith,執行成功後回調list上的函數
if (deferred) deferred.resolveWith(context, [data, status, xhr])
triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
//成功執行完以後完成此次Ajax
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)
//若是是失敗了的話,調用rejectWith,執行失敗後回調list上的函數
if (deferred) deferred.rejectWith(context, [xhr, type, error])
triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
//最後也要完成此次Ajax
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)

//jsonpCallback指的是用戶定義的數據返回時調用的函數
var _callbackName = options.jsonpCallback,
//若是jsonpCallback是函數就返回函數調用結果,不然返回自己,若是_callbackName爲falsy,那麼返回當前jsonpid做爲函數名
callbackName = ($.isFunction(_callbackName) ?
_callbackName() : _callbackName) || ('jsonp' + (++jsonpID)),
script = document.createElement('script'),
//緩存起來callback,由於window[callbackName]會被覆蓋
originalCallback = window[callbackName],
responseData,
//中斷請求函數
abort = function(errorType) {
//觸發腳本元素上的error事件
$(script).triggerHandler('error', errorType || 'abort')
},
xhr = { abort: abort }, abortTimeout

if (deferred) deferred.promise(xhr)

//給腳本綁定load和error事件
$(script).on('load error', function(e, errorType){
//清除掉超時操做
clearTimeout(abortTimeout)
//用完了的腳本刪除掉
$(script).off().remove()

if (e.type == 'error' || !responseData) {
ajaxError(null, errorType || 'error', xhr, options, deferred)
} else {
ajaxSuccess(responseData[0], xhr, options, deferred)
}

window[callbackName] = originalCallback
//若是服務器返回了數據,而且originalCallback爲函數的話,就把數據放進去處理
if (responseData && $.isFunction(originalCallback))
originalCallback(responseData[0])

originalCallback = responseData = undefined
})

//若是ajaxBeforeSend操做返回false的話,就中斷該請求
if (ajaxBeforeSend(xhr, options) === false) {
abort('abort')
return xhr
}

//覆蓋原來的callbackName引用,用來獲取返回的數據,由於服務器是把數據塞進callback返回的 callback({ 「key」: 「vlaue」 });
window[callbackName] = function(){
responseData = arguments
}

//使用請求外鏈腳本的方式向服務器發送請求,把callback添加到參數上
script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName)
document.head.appendChild(script)

//設定超時中斷請求,生成的腳本加載完成就會清除掉
if (options.timeout > 0) abortTimeout = setTimeout(function(){
abort('timeout')
}, options.timeout)

return xhr
}

//Ajax方法的默認參數對象
$.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
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
}

//判斷傳入MIME的類型,轉化爲對應的字符串
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
//查詢第一個出現的&,?等組合,替換爲?,以防原URL結尾帶有符號
return (url + '&' + query).replace(/[&?]{1,2}/, '?')
}

// serialize payload and append it to the URL for GET requests
//處理轉換data和URL
function serializeData(options) {
if (options.processData && options.data && $.type(options.data) != "string")
//自動把非字符串data序列化
options.data = $.param(options.data, options.traditional)
if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
//若是是get請求的話把序列化後的字符串數據追加到URL
options.url = appendQuery(options.url, options.data), options.data = undefined
}

//主方法
$.ajax = function(options){
//建立新對象複製用戶傳進來的非undefined值
var settings = $.extend({}, options || {}),
//若是加載了deferred,callbacks模塊,那麼就實例化一個$.Deferred對象
deferred = $.Deferred && $.Deferred()
//遍歷默認的Ajax參數,若是用戶沒有覆蓋,那麼就是用默認參數值
for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]

//觸發Ajax開始事件及執行對應事件處理函數
ajaxStart(settings)

//若是crossDomain爲falsy值,那麼須要設置,先檢測url是否爲絕對地址(http:// 第二部分不能是/開頭,排除文件地址),用絕對地址表示跨域
//而且再檢測請求url的host時候是否等於當前的host
if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
RegExp.$2 != window.location.host

//若是url爲falsy值,那麼就拿當前地址
if (!settings.url) settings.url = window.location.toString()
serializeData(settings)

//判斷url可否匹配 ?任意字符=? ,匹配表示爲jsonp請求
var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url)
if (hasPlaceholder) dataType = 'jsonp'

if (settings.cache === false || (
(!options || options.cache !== true) &&
//script和JSONP默認緩存
('script' == dataType || 'jsonp' == dataType)
))
//判斷結果爲不緩存的話,給連接帶上時間戳
settings.url = appendQuery(settings.url, '_=' + Date.now())

//若是datatype爲JSONP,可是格式不對的話,須要糾正,而後發起JSONP請求
if ('jsonp' == dataType) {
if (!hasPlaceholder)
settings.url = appendQuery(settings.url,
settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
return $.ajaxJSONP(settings, deferred)
}

//根據數據類型來判斷接收類型
var mime = settings.accepts[dataType],
//用來記錄header信息
headers = { },
setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
//url若是沒有定義請求的協議,那麼就和當前頁面相同
protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
//新建xhr對象
xhr = settings.xhr(),
//緩存原生的定製header方法
nativeSetHeader = xhr.setRequestHeader,
abortTimeout

//把deferred把promise對象上的方法複製給xhr(包含state,always,then,promise,done,fail,progress方法) 如:xhr.done(function(data, status, xhr){ ... })
if (deferred) deferred.promise(xhr)

//若是不是跨域的話,則保存異步請求報頭x-requested-with: XMLHttpRequest
if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest')
//設置接收的數據類型
setHeader('Accept', mime || '*/*')

//調用overrideMimeType覆蓋服務器返回的MIME類型,用自定義的
if (mime = settings.mimeType || mime) {
if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
xhr.overrideMimeType && xhr.overrideMimeType(mime)
}

//設置發送給服務器的內容類型
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')

//設置用戶定義的headers
if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
xhr.setRequestHeader = setHeader

//添加readystatechange監聽事件
//readystatechange事件不會有event 對象,使用this由於scope做用域問題可能致使函數運行失敗或者報錯,所以事件內部引用仍是用xhr
xhr.onreadystatechange = function(){
//當readyState爲4, 請求已完成,且響應已就緒
if (xhr.readyState == 4) {
//取消掉監聽
xhr.onreadystatechange = empty
//取消超時操做
clearTimeout(abortTimeout)
var result, error = false
//判斷響應狀態,一般20幾表明成功了部分數據已經返回,另外304表示那個資源沒有被修改過,直接從瀏覽器緩存拿過來就能夠
//xhr.status == 0 && protocol == 'file:'應該是瀏覽器兼容性問題,例如:Opera 狀態爲204的時候,status收到的爲0
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
//獲取返回的數據類型,用戶有規定的話就不用查服務器返回的了
dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
//保存返回的數據
result = xhr.responseText

try {
// http://perfectionkills.com/global-eval-what-are-the-options/
//若是接收script的話,在全局範圍內運行返回的腳本
//由於默認eval是在當前做用域執行腳本的,所以須要用indirect模式來調用,才能在全局做用域執行腳本
if (dataType == 'script') (1,eval)(result)
//若是要接收的是XML的話,須要訪問xhr的responseXML 屬性才能拿到,responseText是沒有的
else if (dataType == 'xml') result = xhr.responseXML
//若是期待接收的是JSON,那麼先檢測是否爲空,不爲空才把JSON轉化爲javascript對象
else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
} catch (e) { error = e }

//若是error存在,就觸發parsererror事件
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)
}
}
}

//若是ajaxBeforeSend操做返回false的話,就中斷該請求
if (ajaxBeforeSend(xhr, settings) === false) {
xhr.abort()
ajaxError(null, 'abort', xhr, settings, deferred)
return xhr
}

//若是用戶定義了xhrFields對象,把值複製到xhr裏
if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]

//決定是同步的Ajax仍是異步的
var async = 'async' in settings ? settings.async : true
//準備好一個Ajax請求,但還沒發送
xhr.open(settings.type, settings.url, async, settings.username, settings.password)

//定製發送給服務器報頭信息
for (name in headers) nativeSetHeader.apply(xhr, headers[name])

//若是有設置了最長等待時間,就設置一個定製器,超時清空回調中斷請求
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
//爲下面經常使用快捷Ajax轉化正確的參數
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)
}

//把當前集合的HTML內容替換成get 異步請求回來的頁面內容
$.fn.load = function(url, data, success){
if (!this.length) return this
//url 中能夠攜帶一個選擇器,返回的內容結構只有匹配該選擇器的纔會用
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]
//修改請求成功後的處理函數,增長對selector的支持
options.success = function(response){
self.html(selector ?
//若是提供了selector,建立一個div,把內容過濾後放在裏面,而後找到匹配selector的元素,替換self裏的結構
$('<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)
//遍歷data對象
$.each(obj, function(key, value) {
type = $.type(value)
//如若scope存在(第一次執行爲沒有值跳過),那麼是否用傳統方式,是的話返回key爲空
//不是的話若是用戶傳的data爲簡單對象,或者當前值的類型爲object,array的話,返回a[key]給key
//不然返回[]給key
if (scope) key = traditional ? scope :
scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'

// handle data in serializeArray() format
//若是scope不存在,且用戶傳的data是數組,表示用戶傳的data爲[{name:"xx",value:"xx"},{name:"xx2",value:"yy2"}]形式
if (!scope && array) params.add(value.name, value.value)
// recurse into nested objects
//不然若是用戶傳的data爲對象,值是數組( 如:{[],[]} ),或者非傳統方式下,值是對象的形式( 如:{{},{}} ),繼續遍歷裏面的數據
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
//例如數據爲:{num:[1,2,3]}, 傳統方式轉化結果爲:[a=1,a=2,a=3]
//非傳統轉化結果爲:[a[]=1,a[]=2,a[]=3]
else params.add(key, value)
})
}

//將用戶傳的data數據轉換爲查詢字符串的格式
$.param = function(obj, traditional){
var params = []
//給params數組添加一個方法,添加的數據格式爲:encodeURIComponent(name)=encodeURIComponent(value)
params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
serialize(params, obj, traditional)
//%20(空格)替換爲+號
return params.join('&').replace(/%20/g, '+')
}
})(Zepto)


//接下來是表單序列化和提交操做
;(function($){

//過濾出有效的表單字段名和值
$.fn.serializeArray = function() {
var el, type, result = []
//獲取遍歷當前集合下第一個表單全部字段
$([].slice.call(this.get(0).elements)).each(function(){
el = $(this)
type = el.attr('type')
//判斷字段的類型,排除fieldset,不可用,submit,Reset,button,不是radio且同時不是checkbox,若是是radio或者是checkbox,那麼篩選出被選中的,就把該字段添加到result數組裏去
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
}

//將上面過濾出來的數組轉化爲name=1&name2=2的字符串形式
$.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)
//不然,就主動觸發submit事件,而且用submit方法來表單若是沒有preventDefault()的話
//直接javascript調用submit() 提交的話, 不會觸發submit事件
else if (this.length) {
var event = $.Event('submit')
this.eq(0).trigger(event)
if (!event.isDefaultPrevented()) this.get(0).submit()
}
return this
}

})(Zepto)


//接下來是ie模塊,用來支持桌面ie10和手機win8瀏覽器
;(function($){
// __proto__ doesn't exist on IE<11, so redefine
// the Z function to use object extension instead
if (!('__proto__' in {})) {
//不支持__proto__的話,就從新定義Z和isZ方法
$.extend($.zepto, {
Z: function(dom, selector){
dom = dom || []
//用對象拓展的方式來得到$,fn上的方法
$.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
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
//若是getComputedStyle傳入的不是一個有效元素會致使錯誤的話,須要修正一下,放到try中執行
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})(Zepto)


//接下來是檢測模塊,提供系統和瀏覽器信息
;(function($){
function detect(ua){
//在zepto上拓展兩個對象os和browser,用來存儲相關信息,match方法返回一個數組,裏面存放被匹配的結果
var os = this.os = {}, browser = this.browser = {},
webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/),
android = ua.match(/(Android);?[\s\/]+([\d.]+)?/),
osx = !!ua.match(/\(Macintosh\; Intel /),
ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/),
iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),
wp = ua.match(/Windows Phone ([\d.]+)/),
touchpad = webos && ua.match(/TouchPad/),
kindle = ua.match(/Kindle\/([\d.]+)/),
silk = ua.match(/Silk\/([\d._]+)/),
blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/),
bb10 = ua.match(/(BB10).*Version\/([\d.]+)/),
rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/),
playbook = ua.match(/PlayBook/),
chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/),
firefox = ua.match(/Firefox\/([\d.]+)/),
ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),
webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),
safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/)

// Todo: clean this up with a better OS/browser seperation:
// - discern (more) between multiple browsers on android
// - decide if kindle fire in silk mode is android or not
// - Firefox on Android doesn't specify the Android version
// - possibly devide in os, device and browser hashes

if (browser.webkit = !!webkit) browser.version = webkit[1]

if (android) os.android = true, os.version = android[2]
if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.')
if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.')
if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null
if (wp) os.wp = true, os.version = wp[1]
if (webos) os.webos = true, os.version = webos[2]
if (touchpad) os.touchpad = true
if (blackberry) os.blackberry = true, os.version = blackberry[2]
if (bb10) os.bb10 = true, os.version = bb10[2]
if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]
if (playbook) browser.playbook = true
if (kindle) os.kindle = true, os.version = kindle[1]
if (silk) browser.silk = true, browser.version = silk[1]
if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true
if (chrome) browser.chrome = true, browser.version = chrome[1]
if (firefox) browser.firefox = true, browser.version = firefox[1]
if (ie) browser.ie = true, browser.version = ie[1]
if (safari && (osx || os.ios)) {browser.safari = true; if (osx) browser.version = safari[1]}
if (webview) browser.webview = true

os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
(firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)))
os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 ||
(chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
(firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))))
}

detect.call($, navigator.userAgent)
// make available to unit tests
$.__detect = detect

})(Zepto)


//接下來是CSS3動畫模塊
;(function($, undefined){
var prefix = '', eventPrefix, endEventName, endAnimationName,
vendors = { Webkit: 'webkit', Moz: '', O: 'o' },
document = window.document, testEl = document.createElement('div'),
supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
transform,
transitionProperty, transitionDuration, transitionTiming, transitionDelay,
animationName, animationDuration, animationTiming, animationDelay,
cssReset = {}

//將駝峯形式的屬性名轉爲CSS形式:lineHeight => line-height
function dasherize(str) { return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase() }
//給TransitionEnd AnimationEnd事件提添加前綴
function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : name.toLowerCase() }

$.each(vendors, function(vendor, event){
//用來檢測當前瀏覽器適用哪一種前綴
if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
prefix = '-' + vendor.toLowerCase() + '-'
eventPrefix = event
return false
}
})

//給變量賦值,各屬性修改成帶前綴的值,cssReset用來重置動畫屬性,就是把添加上去的樣式在動畫結束後刪掉
transform = prefix + 'transform'
cssReset[transitionProperty = prefix + 'transition-property'] =
cssReset[transitionDuration = prefix + 'transition-duration'] =
cssReset[transitionDelay = prefix + 'transition-delay'] =
cssReset[transitionTiming = prefix + 'transition-timing-function'] =
cssReset[animationName = prefix + 'animation-name'] =
cssReset[animationDuration = prefix + 'animation-duration'] =
cssReset[animationDelay = prefix + 'animation-delay'] =
cssReset[animationTiming = prefix + 'animation-timing-function'] = ''

//動畫的全局設置參數
$.fx = {
//在支持CSS transition的瀏覽器上是返回false的,設爲TRUE禁用動畫過渡
off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
speeds: { _default: 400, fast: 200, slow: 600 },
cssPrefix: prefix,
//transition動畫執行結束時,觸發webkitTransitionEnd事件 如:-webkit-transition: width 0.25s ease-in;
transitionEnd: normalizeEvent('TransitionEnd'),
//animation(keyframe)動畫執行結束時,觸發webkitAnimationEnd事件 如:-webkit-animation: animateFn 0.5s ease-in;
animationEnd: normalizeEvent('AnimationEnd')
}

//動畫animate的接口,對傳進來的參數進行分析判斷,從新賦值
$.fn.animate = function(properties, duration, ease, callback, delay){
if ($.isFunction(duration))
callback = duration, ease = undefined, duration = undefined
if ($.isFunction(ease))
callback = ease, ease = undefined
if ($.isPlainObject(duration))
ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration
if (duration) duration = (typeof duration == 'number' ? duration :
($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
if (delay) delay = parseFloat(delay) / 1000
return this.anim(properties, duration, ease, callback, delay)
}

$.fn.anim = function(properties, duration, ease, callback, delay){
var key, cssValues = {}, cssProperties, transforms = '',
that = this, wrappedCallback, endEvent = $.fx.transitionEnd,
fired = false

if (duration === undefined) duration = $.fx.speeds._default / 1000
if (delay === undefined) delay = 0
//若是off被人設爲TRUE,或者不支持的話,沒有動畫,直接跳到最終樣式
if ($.fx.off) duration = 0

//若是傳入的properties是一個動畫名
if (typeof properties == 'string') {
// keyframe animation
cssValues[animationName] = properties
cssValues[animationDuration] = duration + 's'
cssValues[animationDelay] = delay + 's'
//默認採用linear速度
cssValues[animationTiming] = (ease || 'linear')
endEvent = $.fx.animationEnd
} else {
cssProperties = []
// CSS transitions
for (key in properties)
//若是是translate rotate等transform變形狀況,就須要用它們的語法
if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
//不然就保存屬性值,和轉化好的屬性名
else cssValues[key] = properties[key], cssProperties.push(dasherize(key))

if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
if (duration > 0 && typeof properties === 'object') {
//須要多個屬性變化的話用,來分割 transition-property: width,height;
cssValues[transitionProperty] = cssProperties.join(', ')
cssValues[transitionDuration] = duration + 's'
cssValues[transitionDelay] = delay + 's'
cssValues[transitionTiming] = (ease || 'linear')
}
}

wrappedCallback = function(event){
if (typeof event !== 'undefined') {
if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
$(event.target).unbind(endEvent, wrappedCallback)
} else
//由於transitionEnd事件不能保證被觸發,所以這裏的狀況就是針對沒有觸發的,經過下面定時來主動執行事件,把添加的事件監聽移除
$(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout

fired = true
//把添加上去的CSS動畫屬性清除,這樣keyframe下次才能繼續生效
$(this).css(cssReset)
//到這裏纔是執行用戶定義的回調
callback && callback.call(this)
}
if (duration > 0){
//綁定動畫完成事件監聽
this.bind(endEvent, wrappedCallback)
// transitionEnd is not always firing on older Android phones
// so make sure it gets fired
setTimeout(function(){
if (fired) return
wrappedCallback.call(that)
}, (duration * 1000) + 25)
}

// trigger page reflow so new elements can animate
this.size() && this.get(0).clientLeft

//設置CSS執行動畫
this.css(cssValues)

if (duration <= 0) setTimeout(function() {
that.each(function(){ wrappedCallback.call(this) })
}, 0)

return this
}

//釋放內存
testEl = null
})(Zepto)

 

//接下來這個模塊是預約義的動畫方法,在上面animate方法上封裝
;(function($, undefined){
var document = window.document, docElem = document.documentElement,
origShow = $.fn.show, origHide = $.fn.hide, origToggle = $.fn.toggle

//下面各類動畫是調用這個函數在調用animate以前對參數進行預處理
function anim(el, speed, opacity, scale, callback) {
if (typeof speed == 'function' && !callback) callback = speed, speed = undefined
var props = { opacity: opacity }
//經過scale變形來實現放大縮小的顯隱效果
if (scale) {
props.scale = scale
//定義旋轉的中心點
el.css($.fx.cssPrefix + 'transform-origin', '0 0')
}
return el.animate(props, speed, null, callback)
}

function hide(el, speed, scale, callback) {
return anim(el, speed, 0, scale, function(){
//動畫結束後調用舊方法讓當前元素集合消失
origHide.call($(this))
//而後再觸發用戶定義的回調
callback && callback.call(this)
})
}

//把show指向新的函數,添加對動畫週期,回調函數的支持
$.fn.show = function(speed, callback) {
//origShow是原來的show方法,例如原來的元素是display:none,那麼調用這個能夠display:block,後面立刻css('opacity', 0)變成透明
origShow.call(this)
if (speed === undefined) speed = 0
else this.css('opacity', 0)
//這裏的縮放scale(1,1)是對應下面hide方法,若是沒有執行過帶speed參數的hide方法,是不會有縮放效果
return anim(this, speed, 1, '1,1', callback)
}

//把hide指向新的函數
$.fn.hide = function(speed, callback) {
//若是沒有傳參數,調用舊的hide方法就能夠
if (speed === undefined) return origHide.call(this)
//若是傳入了speed參數,經過這裏的縮放scale(0,0),就會有縮小效果,下次調用show也會有放大效果(由於被縮成小了)
else return hide(this, speed, '0,0', callback)
}

//把toggle指向新的函數
$.fn.toggle = function(speed, callback) {
//沒有傳入speed或者speed返回布爾值的話,就使用原來的toggle方法
if (speed === undefined || typeof speed == 'boolean')
return origToggle.call(this, speed)
//不然遍歷當前集合,判斷目前的display狀態,而後調用show,或者hide方法
else return this.each(function(){
var el = $(this)
el[el.css('display') == 'none' ? 'show' : 'hide'](speed, callback)
})
}

//把透明度漸變到指定數值
$.fn.fadeTo = function(speed, opacity, callback) {
return anim(this, speed, opacity, null, callback)
}

//元素漸變出來
$.fn.fadeIn = function(speed, callback) {
var target = this.css('opacity')
//若是當前是不透明的,那麼就把透明度該爲0,而後再進行漸變
if (target > 0) this.css('opacity', 0)
//若是當前是透明或者display:none的,那麼就先顯示出來,而後再把透明度漸變到1
else target = 1
return origShow.call(this).fadeTo(speed, target, callback)
}

$.fn.fadeOut = function(speed, callback) {
return hide(this, speed, null, callback)
}

$.fn.fadeToggle = function(speed, callback) {
return this.each(function(){
var el = $(this)
//經過判斷當前透明度或display來決定使用fadein仍是fadeout
el[
(el.css('opacity') == 0 || el.css('display') == 'none') ? 'fadeIn' : 'fadeOut'
](speed, callback)
})
}

})(Zepto)


//實驗性質的模塊,在IOS上移除圖片元素以後回收內存
;(function($){
var cache = [], timeout

$.fn.remove = function(){
return this.each(function(){
if(this.parentNode){
if(this.tagName === 'IMG'){
//緩存對img對象的引用
cache.push(this)
//這是一個1*1無內容的圖,把圖片的內容指向它,由於src是指向圖片資源地址(內存地址),先去掉對內存地址的引用(回收內存),而後移除img元素,最後清除對img節點的引用?
this.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
if (timeout) clearTimeout(timeout)
//一段時間後清除掉緩存的對img的引用
timeout = setTimeout(function(){ cache = [] }, 60000)
}
this.parentNode.removeChild(this)
}
})
}
})(Zepto)


//如下模塊添加對任意對象數據存儲的支持
;(function($){
//data對象就是用來存放每一個元素對應數據集的地方
var data = {}, dataAttr = $.fn.data, camelize = $.camelCase,
exp = $.expando = 'Zepto' + (+new Date()), emptyArray = []

// Get value from node:
// 1. first try key as given,
// 2. then try camelized key,
// 3. fall back to reading "data-*" attribute.
function getData(node, name) {
//獲取元素的id,經過id獲取在data對象中的數據集
var id = node[exp], store = id && data[id]
//若是沒有穿傳name,就返回整個數據集,沒有數據集的話轉化爲設置操做
if (name === undefined) return store || setData(node)
else {
if (store) {
//name屬性在數據集有的話,返回對應數據
if (name in store) return store[name]
//不行嘗試將name轉爲駝峯形式查找
var camelName = camelize(name)
if (camelName in store) return store[camelName]
}
//上面都查找不到的話就用原來的data方法去該元素上查找對應的data-*屬性
return dataAttr.call($(node), name)
}
}

// Store value under camelized key on node
function setData(node, name, value) {
//獲取id,沒有的話賦一個,而且在元素上也保存
var id = node[exp] || (node[exp] = ++$.uuid),
//獲取id對象的數據集,沒有的話讀取元素節點上的全部data-*屬性
store = data[id] || (data[id] = attributeData(node))
//若是name不爲undefined的話,就把駝峯化以後的name做爲key,和對應value一塊兒保存到store對象上
if (name !== undefined) store[camelize(name)] = value
return store
}

// Read all "data-*" attributes from a node
function attributeData(node) {
var store = {}
//經過attributes來獲取元素上的屬性集合
$.each(node.attributes || emptyArray, function(i, attr){
//檢測每一個屬性名是否是以data-開頭,attr獲取: id="a",那麼attr.name爲"id"
if (attr.name.indexOf('data-') == 0)
//屬性名去掉data-以後駝峯化做爲屬性名,value則以本來的數據類型來保存
store[camelize(attr.name.replace('data-', ''))] =
$.zepto.deserializeValue(attr.value)
})
//返回數據集
return store
}

//設置或者查詢數據操做
$.fn.data = function(name, value) {
return value === undefined ?
// set multiple values via object
//沒傳value,表示以對象的形式把數據傳了進來
$.isPlainObject(name) ?
//若是name是對象的話,就遍歷當前集合,再遍歷傳進來的對象給每一個元素設置數據
this.each(function(i, node){
$.each(name, function(key, value){ setData(node, key, value) })
}) :
// get value from first element
//若是傳的那麼是字符串的話,就返回第一個元素中對應的數據,沒有元素的返回undefined給value
(0 in this ? getData(this[0], name) : undefined) :
// set value on all elements
//若是value不爲undefined的話,直接調用setData來設值
this.each(function(){ setData(this, name, value) })
}

//刪除數據操做
$.fn.removeData = function(names) {
//切割字符串爲數組
if (typeof names == 'string') names = names.split(/\s+/)
return this.each(function(){
var id = this[exp], store = id && data[id]
if (store) $.each(names || store, function(key){
//逐個刪除,若是存在names對象,那麼就刪除對應的,不然該元素的數據所有刪除
delete store[names ? camelize(this) : key]
})
})
}

// Generate extended `remove` and `empty` functions
;['remove', 'empty'].forEach(function(methodName){
var origFn = $.fn[methodName]
$.fn[methodName] = function() {
//獲取該集合下全部子集
var elements = this.find('*')
//remove操做相對empty多了一步,把當前元素添加到他的子元素尾部,由於要配合empty方法(看下面註釋),remove是須要把當前元素及其子節點的清掉,因此當前元素添加進elements
if (methodName === 'remove') elements = elements.add(this)
//empty方法是隻清除掉裏面的元素及其數據,因此這裏不能用this.removeData(),否則連當前元素的數據也會清掉
elements.removeData()
return origFn.call(this)
}
})
})(Zepto)

 

//接下來這個是Deferred模塊,須要配合後面callbacks模塊一塊兒用,能夠把多個回調添加到回調隊列,觸發回調對象等,例如xhr.done(function(data, status, xhr){ ... }),這裏xhr就是一個promises
;(function($){
var slice = Array.prototype.slice

function Deferred(func) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", $.Callbacks({once:1, memory:1}), "resolved" ],
[ "reject", "fail", $.Callbacks({once:1, memory:1}), "rejected" ],
[ "notify", "progress", $.Callbacks({memory:1}) ]
],
state = "pending",
promise = {
//獲取當前Deferred實例的狀態
state: function() {
return state
},
//這個方式就是把回調函數同時添加到成功和失敗的執行列表,不管成敗都執行須要執行這個函數意思
always: function() {
deferred.done(arguments).fail(arguments)
return this
},
//調用該方法先進行一些操做,原理內部建立一個deferred對象,返回promise對象(deferred對象的子集)
//var defer = $.Deferred(),
// filtered = defer.then(function( value ) {
// return value * 2;
// });
// defer.resolve( 5 );
// filtered.done(function( value ) {
// $( "body" ).html( "Value is ( 2*5 = : " + value );
// });
// $( "body" ).on( "click", filterResolve );
then: function(/* fnDone [, fnFailed [, fnProgress]] */) {
var fns = arguments
//由於Deferred傳了函數進去的話,會把deferred做爲參數傳進來
return Deferred(function(defer){
$.each(tuples, function(i, tuple){
//傳進來的參數是函數就保存函數,不然爲false
var fn = $.isFunction(fns[i]) && fns[i]
//調用deferred對象上的done,fail,progress方法,添加到各自事件處理函數列表中
deferred[tuple[1]](function(){
//這裏執行用戶傳的事件處理函數,this爲用戶調用Ajax是傳的context,並保存返回值
var returned = fn && fn.apply(this, arguments)
//接下來須要觸發新建立的deferred對象上對應的事件,如上面例子的done,並把返回值傳進去
//若是執行後返回deferred對象( 如返回一個xhr: return $.ajax(...); ),那麼把對應事件觸發函數添加上去(從新綁定執行上下文),例如當xhr完成後觸發done隊列,首先是觸發resolveWith,判斷context
if (returned && $.isFunction(returned.promise)) {
returned.promise()
.done(defer.resolve)
.fail(defer.reject)
.progress(defer.notify)
} else {
//若是沒有返回deferred對象,那麼直接調用resolveWith,rejectWith,notifyWith,觸發新生成的deferred對象上對應的事件(由於是綁定在這上面的,如上面例子)
var context = this === promise ? defer.promise() : this,
values = fn ? [returned] : arguments
defer[tuple[0] + "With"](context, values)
}
})
})
fns = null
}).promise()
},

promise: function(obj) {
return obj != null ? $.extend( obj, promise ) : promise
}
},
//這個是返回的接口對象 var myDeferred = $.Deferred()
deferred = {}

$.each(tuples, function(i, tuple){
//獲取callback對象實例
var list = tuple[2],
//獲取最終狀態碼
stateString = tuple[3]
//生成不一樣狀態(done,fail,progress)事件添加方法,拓展到輸出接口上
promise[tuple[1]] = list.add

//若是存在最終狀態,那麼給回調列表添加三個方法
if (stateString) {
list.add(function(){
//把改變當前Deferred實例狀態的方法添加到回調列表中
state = stateString
//注意這裏添加的第二個方法使用了位運算0^1=>1,1^1=>0
//0意味着已解決狀態,因此禁用掉失敗後調用的list對象,鎖住進行中(progress)的list列表,不能再執行,由於都出結果了,要麼成功要麼失敗
//1意味着失敗狀態,所以禁用掉成功之後才執行的list,一樣鎖住progress
//也就是說當觸發成功或失敗事件的回調list時,第一個執行的回調是改變狀態,而後是廢棄掉與之相對的事件list,而後鎖住progress,而後纔是執行用戶定義的函數
}, tuples[i^1][2].disable, tuples[2][2].lock)
}

//觸發不一樣狀態list上函數的方法(resolve,reject,notify),拓展到輸出接口上
deferred[tuple[0]] = function(){
deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments)
return this
}
//生成不一樣狀態下配置觸發回調參數的方法(resolveWith,rejectWith,notifyWith),拓展到輸出接口上
deferred[tuple[0] + "With"] = list.fireWith
})

//拓展輸出的接口對象,把promise對象裏的方法也複製進去
promise.promise(deferred)
//若是實例化的時候傳入了函數,把deferred做爲上下文並做爲參數傳進去(上面then方法)
if (func) func.call(deferred, deferred)
//返回接口
return deferred
}

//該方法提供基於一個或多個對象運行回調的功能
$.when = function(sub) {
//複製傳進來的參數
var resolveValues = slice.call(arguments),
len = resolveValues.length,
i = 0,
//若是傳進來的參數存在且length等於1,就判斷是否是Promise,是返回1,不是返回0
remain = len !== 1 || (sub && $.isFunction(sub.promise)) ? len : 0,
//根據狀況生成deferred對象,有傳進來就用傳進來的,沒有生成一個
deferred = remain === 1 ? sub : Deferred(),
progressValues, progressContexts, resolveContexts,

updateFn = function(i, ctx, val){
return function(value){
//this指向fireWith的context(運行時爲this),一樣value爲fireWith的arguments
ctx[i] = this
val[i] = arguments.length > 1 ? slice.call(arguments) : value
//若是傳進來的progressValues添加當前參數後等於progressValues,那麼表示正在處理
if (val === progressValues) {
deferred.notifyWith(ctx, val)
//remain減到0觸發resolveWith(done)
} else if (!(--remain)) {
deferred.resolveWith(ctx, val)
}
}
}

//若是傳進多個對象
if (len > 1) {
//由於知道了數組的長度,用new Array(len)方式建立
progressValues = new Array(len)
progressContexts = new Array(len)
resolveContexts = new Array(len)
//遍歷傳進來的參數
for ( ; i < len; ++i ) {
//若是是Deferred或Promise
if (resolveValues[i] && $.isFunction(resolveValues[i].promise)) {
//給每一個promise添加事件處理,updateFn用來更新觸發各自事件的參數
resolveValues[i].promise()
.done(updateFn(i, resolveContexts, resolveValues))
.fail(deferred.reject)
.progress(updateFn(i, progressContexts, progressValues))
} else {
--remain
}
}
}

//傳進來的參數既不是Deferred 又不是Promise,觸發resolveWith方法(done)
if (!remain) deferred.resolveWith(resolveContexts, resolveValues)
//返回promise對象(deferred對象的子集)
return deferred.promise()
}

$.Deferred = Deferred
})(Zepto)

 

//接下這個模塊定義了回調函數的隊列,能夠添加或觸發這裏面的函數,使用:
//var myCallback = $.Callbacks({once:true});
//myCallback.add(fun1);
//myCallback.add(fun2);
//myCallback.fire();
;(function($){
// Create a collection of callbacks to be fired in a sequence, with configurable behaviour
// Option flags:
// - once: Callbacks fired at most one time.
// - memory: Remember the most recent context and arguments
// - stopOnFalse: Cease iterating over callback list
// - unique: Permit adding at most one instance of the same callback
$.Callbacks = function(options) {
//複製用戶傳的配置參數到一個新對象裏
options = $.extend({}, options)

//建立這個模塊私有的成員屬性
var memory, // Last fire value (for non-forgettable lists)
fired, // Flag to know if list was already fired
firing, // Flag to know if list is currently firing
firingStart, // First callback to fire (used internally by add and fireWith)
firingLength, // End of the loop when firing
firingIndex, // Index of currently firing callback (modified by remove if needed)
list = [], // Actual callback list
stack = !options.once && [], // Stack of fire calls for repeatable lists
//觸發list上函數的方法,data是個數組,包含實例對象和參數們
fire = function(data) {
//若是設置了須要記住上次最後的對象和參數,把麼就把fire的參數存在memory裏
memory = options.memory && data
//設爲已經觸發過狀態
fired = true
//設置目前觸發到哪裏位置
firingIndex = firingStart || 0
//設置開始觸發的位置
firingStart = 0
//設置循環的長度
firingLength = list.length
//設置爲觸發中狀態
firing = true
for ( ; list && firingIndex < firingLength ; ++firingIndex ) {
//從數組第一個開始循環,若是在循環的時候,有一個回調執行完返回false結果,而且設置了stopOnFalse的話,退出循環,memory也就爲false
if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) {
memory = false
break
}
}
//到這裏list已經執行完了(不論成敗),因此把正在執行狀態關了
firing = false
if (list) {
//若是是可重複執行模式(默認模式),那麼就從頭開始執行,調用$.Callbacks().fired()多少次重複多少次
if (stack) stack.length && fire(stack.shift())
//不然在不可重複模式下若是沒有異常的話,就把list數組清空
else if (memory) list.length = 0
//若是上面狀況都不成立,就禁用掉整個模塊
else Callbacks.disable()
}
},

//這個是返回的接口對象
Callbacks = {
//添加回調函數到回調隊列裏
add: function() {
if (list) {
var start = list.length,
add = function(args) {
//遍歷傳進來的參數
$.each(args, function(_, arg){
//若是當前參數爲函數
if (typeof arg === "function") {
//若是用戶沒有設置同一個函數只容許添加一次,或者限制了可是目前的列表裏沒有該函數,就把該函數添加到隊列裏
if (!options.unique || !Callbacks.has(arg)) list.push(arg)
}
//若是是當前參數爲數組,那麼繼續調用add方法,遍歷當前參數裏面的內容
else if (arg && arg.length && typeof arg !== 'string') add(arg)
})
}
add(arguments)

//若是正在觸發回調列表裏的函數,由於list尾部增長了數據,因此要更新firingLength總長度,由於它是緩存了list的長度不會自動更新
if (firing) firingLength = list.length
//若是當前沒有在觸發的話,就查看是否存在上一次最後的data(實例對象和參數)
else if (memory) {
//有的話,定位開始觸發地點,也就是沒有添加新的回調函數以前列表的結尾
firingStart = start
//開始從上次結束位置觸發回調,由於start是長度值,比list數組索引+1,因此直接執行新添加的回調
fire(memory)
}
}
return this
},
//從回調列表裏移除回調函數
remove: function() {
if (list) {
$.each(arguments, function(_, arg){
var index
//查看給的函數是否在回調列表裏,inArray會返回在匹配到的目標在數組中的索引
while ((index = $.inArray(arg, list, index)) > -1) {
//找到的話就刪除它,注意這樣數組長度是會-1的
list.splice(index, 1)
// Handle firing indexes
//若是list正在觸發的話
if (firing) {
//由於list被刪掉一個,因此循環次數也應該-1
if (index <= firingLength) --firingLength
//若是被刪除的回調是已經執行過的,至關於整個數組裏面內容向前移動一格,所以當前的索引也須要-1,否則會錯過一個回調
if (index <= firingIndex) --firingIndex
}
}
})
}
return this
},
//判斷傳進來的函數list有沒有,若是沒有傳參數或傳的不是函數,返回TRUE
has: function(fn) {
return !!(list && (fn ? $.inArray(fn, list) > -1 : list.length))
},
//清空目前list裏的函數,但之後能夠再進行操做
empty: function() {
firingLength = list.length = 0
return this
},
//設爲不可用,也就是當前實例對象做廢了,沒法添加刪除觸發等等
disable: function() {
list = stack = memory = undefined
return this
},
//檢測當前Callback實例對象是否被禁用了
disabled: function() {
return !list
},
//鎖住,調用之後就不能再觸發fire()
lock: function() {
stack = undefined;
if (!memory) Callbacks.disable()
return this
},
//看當前實例對象是否鎖住
locked: function() {
return !stack
},
//綁定實例對象和附加參數
fireWith: function(context, args) {
//若是list存在而且沒有觸發過,或者觸發過了但爲可重複執行模式
if (list && (!fired || stack)) {
args = args || []
//把當前實例對象和額外參數做爲data,可使用slice的話就複製一份不共用
args = [context, args.slice ? args.slice() : args]
//若是正在觸發,那麼就保存到stack數組裏,等到list觸發完了再觸發
if (firing) stack.push(args)
//不然直接觸發
else fire(args)
}
return this
},
//傳入附加參數,正式開始,this指向實例對象
fire: function() {
return Callbacks.fireWith(this, arguments)
},
//看list是否被觸發過了
fired: function() {
return !!fired
}
}

return Callbacks
}
})(Zepto)

 

//接下來這個模塊提供了實驗性質的選擇器拓展 例如:$('div:first') 或者 el.is(':visible')
;(function($){
//首先,保存舊的方法
var zepto = $.zepto, oldQsa = zepto.qsa, oldMatches = zepto.matches

//判斷元素是否可見
function visible(elem){
elem = $(elem)
//若是元素有高度或者寬度(不能爲0)就返回數值,不然返回false,而且不能設置了none
return !!(elem.width() || elem.height()) && elem.css("display") !== "none"
}

// Implements a subset from:
// http://api.jquery.com/category/selectors/jquery-selector-extensions/
//
// Each filter function receives the current index, all nodes in the
// considered set, and a value if there were parentheses. The value
// of `this` is the node currently being considered. The function returns the
// resulting node(s), null, or undefined.
//
// Complex selectors are not supported:
// li:has(label:contains("foo")) + li:has(label:contains("bar"))
// ul.inner:first > li

//obj[':'] = {} 是在原有對象上拓展,若是直接 obj = {}的話,是會建立一個新對象而後把obj指向新對象,而不是在原來對象上拓展
var filters = $.expr[':'] = {
visible: function(){ if (visible(this)) return this },
hidden: function(){ if (!visible(this)) return this },
selected: function(){ if (this.selected) return this },
checked: function(){ if (this.checked) return this },
parent: function(){ return this.parentNode },
first: function(idx){ if (idx === 0) return this },
last: function(idx, nodes){ if (idx === nodes.length - 1) return this },
eq: function(idx, _, value){ if (idx === value) return this },
contains: function(idx, _, text){ if ($(this).text().indexOf(text) > -1) return this },
has: function(idx, _, sel){ if (zepto.qsa(this, sel).length) return this }
}

//匹配div:first等帶僞類的選擇器
var filterRe = new RegExp('(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*'),
//匹配 >開頭的選擇器
childRe = /^\s*>/,
//(+new Date()) 至關於 (new Date()).getTime()
classTag = 'Zepto' + (+new Date())

//這個函數主要是處理切割判斷selector
function process(sel, fn) {
// quote the hash in `a[href^=#]` expression
sel = sel.replace(/=#\]/g, '="#"]')
//使用正則對象的exec方法能夠返回結果數組,沒有的話返回null
var filter, arg, match = filterRe.exec(sel)
//match[2]返回的是第二個表達式匹配的內容(也就是 : 後面第一對括號匹配到的),例如:first :visible等,再查找filters裏有沒有對應方法
if (match && match[2] in filters) {
//保存找到的方法,額外參數和選擇器。 額外的參數例如:$("#k:contains('k')")
filter = filters[match[2]], arg = match[3]
sel = match[1]
if (arg) {
//額外的參數若是能夠轉化爲數字就轉化
var num = Number(arg)
if (isNaN(num)) arg = arg.replace(/^["']|["']$/g, '')
else arg = num
}
}
return fn(sel, filter, arg)
}

//把zepto.qsa指向新函數
zepto.qsa = function(node, selector) {
return process(selector, function(sel, filter, arg){
try {
var taggedParent
//若是選擇器不存在,可是僞元素存在 如:el.is(':visible')狀況
if (!sel && filter) sel = '*'
//若是選擇的是下一級子選擇器狀況
else if (childRe.test(sel))
// support "> *" child queries by tagging the parent node with a
// unique class and prepending that classname onto the selector
//給當前選中元素(一般是document)添加一個惟一的類,而後把選擇器改成該類後代下的選擇器
taggedParent = $(node).addClass(classTag), sel = '.'+classTag+' '+sel

//調用舊的querySelectorAll方法獲取匹配元素
var nodes = oldQsa(node, sel)
} catch(e) {
console.error('error performing selector: %o', selector)
throw e
} finally {
if (taggedParent) taggedParent.removeClass(classTag)
}
return !filter ? nodes :
//有僞類選擇器的狀況,在選出的集合裏逐個調用filter方法,符合條件的話會返回對象,否者返回undefined的會被map過濾掉
zepto.uniq($.map(nodes, function(n, i){ return filter.call(n, i, nodes, arg) }))
})
}

zepto.matches = function(node, selector){
return process(selector, function(sel, filter, arg){
return (!sel || oldMatches(node, sel)) &&
(!filter || filter.call(node, null, arg) === node)
})
}
})(Zepto)


//接下來這個模塊提供觸屏事件支持
;(function($){
var touch = {},
touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
//觸發長按的時間
longTapDelay = 750,
gesture

//肯定滑動方向
function swipeDirection(x1, x2, y1, y2) {
//首先判斷垂直方向改變差值和水平方向差值哪一個大,而後若是是水平方向大的話再肯定向左仍是向右滑動
return Math.abs(x1 - x2) >=
Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}

//觸發長按事件
function longTap() {
//把定時器回收
longTapTimeout = null
if (touch.last) {
touch.el.trigger('longTap')
touch = {}
}
}

//取消掉會觸發長按事件的定時器
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout)
//回收
longTapTimeout = null
}

//取消全部事件的觸發
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout)
if (tapTimeout) clearTimeout(tapTimeout)
if (swipeTimeout) clearTimeout(swipeTimeout)
if (longTapTimeout) clearTimeout(longTapTimeout)
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
touch = {}
}


function isPrimaryTouch(event){
//pointer事件裏面的pointerType屬性能夠得到源事件是哪種: touch pen mouse
return (event.pointerType == 'touch' ||
event.pointerType == event.MSPOINTER_TYPE_TOUCH)
//isPrimary屬性用來判斷 primary pointer是否是在當前頁面上的
&& event.isPrimary
}

//判斷是否是pointer事件類型,由於在window手機裏是觸發pointer事件
function isPointerEventType(e, type){
return (e.type == 'pointer'+type ||
e.type.toLowerCase() == 'mspointer'+type)
}

$(document).ready(function(){
var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType

//若是微軟的手勢對象存在,這個對象已經封裝好了各類手勢,不須要本身去處理識別
if ('MSGesture' in window) {
gesture = new MSGesture()
gesture.target = document.body
}

$(document)
//MSGestureEnd事件當觸碰物都離開屏幕,屏幕上沒有活動時觸發
.bind('MSGestureEnd', function(e){
//velocityX屬性得到x軸運動速度,velocityY得到y軸運動速度,能夠用來判斷方向
var swipeDirectionFromVelocity =
e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
//若是獲取到方向值的話,就觸發滑動和滑動+方向事件(例如 swipeleft)
if (swipeDirectionFromVelocity) {
touch.el.trigger('swipe')
touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
}
})
//touch事件是處理觸控事件,pointer事件則是把mouse,pen,touch事件都統一管理的事件
//蛋疼的是,目前基本上就IE(10+)支持pointer(但和標準有點不一樣 http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh441233.aspx#events)
//其餘的瀏覽器,都僅支持 touch ,但 IE 不支持touch,搞了一套MSGesture,因此兼容吧
//MSPointerDown是微軟早期實現時帶有前綴,ie(11+)開始去掉
.on('touchstart MSPointerDown pointerdown', function(e){
//若是是pointerdown事件(button屬性不爲0時觸發,button指的是pointer設備哪一個按鈕被按下了,例如鼠標上按鈕,觸控筆上的按鈕)
//而且primary pointer不是當前頁面的話,就退出
if((_isPointerType = isPointerEventType(e, 'down')) &&
!isPrimaryTouch(e)) return
//若是是pointer的話,用e來獲取第一個觸碰點信息。touch事件把全部觸碰點信息保存在touches屬性數組裏,0獲取第一個觸碰點
firstTouch = _isPointerType ? e : e.touches[0]
//以防萬一,清除之前可能殘留的觸控座標數據
if (e.touches && e.touches.length === 1 && touch.x2) {
// Clear out touch movement data if we have it sticking around
// This can occur if touchcancel doesn't fire due to preventDefault, etc.
touch.x2 = undefined
touch.y2 = undefined
}
now = Date.now()
//本次觸控和上次觸控的時差,用來判斷是否是雙擊
delta = now - (touch.last || now)
//獲取被觸摸目標元素名稱,當前節點沒有的話獲取父節點(例如文字節點)
touch.el = $('tagName' in firstTouch.target ?
firstTouch.target : firstTouch.target.parentNode)
//取消掉觸發單擊事件的定時器,由於多是雙擊
touchTimeout && clearTimeout(touchTimeout)
//獲取觸摸點在頁面內座標
touch.x1 = firstTouch.pageX
touch.y1 = firstTouch.pageY
//若是時差屬於雙擊狀況,那麼就設置雙擊事件爲真
if (delta > 0 && delta <= 250) touch.isDoubleTap = true
//保存此次的觸控開始的事件,做爲下一次觸控的last時間
touch.last = now
//設置長按定時器,在longTapDelay定義的時間內沒有被取消就觸發長按事件
longTapTimeout = setTimeout(longTap, longTapDelay)
// adds the current touch contact for IE gesture recognition
//若是MSGesture事件存在,那麼把當前接觸點添加到MSGesture實例
if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
})
//添加在觸屏上移動事件的監聽
.on('touchmove MSPointerMove pointermove', function(e){
if((_isPointerType = isPointerEventType(e, 'move')) &&
!isPrimaryTouch(e)) return
firstTouch = _isPointerType ? e : e.touches[0]
//取消長按定時,由於已經在屏幕上移動了
cancelLongTap()
//把移動時的座標保存起來
touch.x2 = firstTouch.pageX
touch.y2 = firstTouch.pageY
//注意這裏是保存每次移動時新座標和源觸碰點的差值
deltaX += Math.abs(touch.x1 - touch.x2)
deltaY += Math.abs(touch.y1 - touch.y2)
})
//添加離開觸屏事件監聽
.on('touchend MSPointerUp pointerup', function(e){
if((_isPointerType = isPointerEventType(e, 'up')) &&
!isPrimaryTouch(e)) return
//離開屏幕若是長按事件觸發了,就把定時器標示符設爲null。沒有觸發就取消定時器。
cancelLongTap()

// swipe
//若是有移動而且移動距離大於30,觸發移動事件
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))

//經過定時來定位,例如用戶實際上是但願滾動頁面,那麼就能夠定位各個觸控事件並取消掉他們
swipeTimeout = setTimeout(function() {
touch.el.trigger('swipe')
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
//清空觸屏產生的數據
touch = {}
}, 0)

// normal tap
else if ('last' in touch)
// don't fire tap when delta position changed by more than 30 pixels,
// for instance when moving to a point and back to origin
if (deltaX < 30 && deltaY < 30) {
// delay by one tick so we can cancel the 'tap' event if 'scroll' fires
// ('tap' fires before 'scroll')
tapTimeout = setTimeout(function() {

// trigger universal 'tap' with the option to cancelTouch()
// (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
var event = $.Event('tap')
//用戶若是調用cancelTouch方法的話,就把全部事件處理和touch數據都清掉了,所以就不用等250毫秒才觸發單擊,能夠實現更加快速單擊觸屏響應
event.cancelTouch = cancelAll
touch.el.trigger(event)

// trigger double tap immediately
if (touch.isDoubleTap) {
if (touch.el) touch.el.trigger('doubleTap')
touch = {}
}

// trigger single tap after 250ms of inactivity
else {
touchTimeout = setTimeout(function(){
touchTimeout = null
if (touch.el) touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}, 0)
} else {
touch = {}
}
deltaX = deltaY = 0

})
// when the browser window loses focus,
// for example when a modal dialog is shown,
// cancel all ongoing events
.on('touchcancel MSPointerCancel pointercancel', cancelAll)

// scrolling the window indicates intention of the user
// to scroll, not tap or swipe, so cancel all ongoing events
$(window).on('scroll', cancelAll)
})

//生成各類手勢事件監聽方法
;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){
$.fn[eventName] = function(callback){ return this.on(eventName, callback) }
})
})(Zepto)

 

//接下來這個模塊封裝了IOS的放大縮小手勢
//在IOS 2.0的瀏覽器以後引入 (https://developer.apple.com/library/safari/documentation/UserExperience/Reference/GestureEventClassReference/GestureEvent/GestureEvent.html)
;(function($){
if ($.os.ios) {
var gesture = {}, gestureTimeout

function parentIfText(node){
return 'tagName' in node ? node : node.parentNode
}

//當兩個手指放在屏幕上時觸發
$(document).bind('gesturestart', function(e){
//獲取當前時間,以及求時間差
var now = Date.now(), delta = now - (gesture.last || now)
gesture.target = parentIfText(e.target)
gestureTimeout && clearTimeout(gestureTimeout)
//獲取兩根手指間的距離
gesture.e1 = e.scale
gesture.last = now
//當兩個手指都在觸屏上移動時觸發
}).bind('gesturechange', function(e){
//獲取移動時兩個手指間的距離
gesture.e2 = e.scale
//當第二根手指離開屏幕時觸發
}).bind('gestureend', function(e){
//若是兩個手指都有移動過
if (gesture.e2 > 0) {
//根據開始距離和最後結束移動時的距離來計算有沒有縮放,再判斷是放大仍是縮小
Math.abs(gesture.e1 - gesture.e2) != 0 && $(gesture.target).trigger('pinch') &&
$(gesture.target).trigger('pinch' + (gesture.e1 - gesture.e2 > 0 ? 'In' : 'Out'))
gesture.e1 = gesture.e2 = gesture.last = 0
//手指沒有移動過就清除數據
} else if ('last' in gesture) {
gesture = {}
}
})

//生成縮放事件監聽方法
;['pinch', 'pinchIn', 'pinchOut'].forEach(function(m){
$.fn[m] = function(callback){ return this.bind(m, callback) }
})
}
})(Zepto)


//接下來這個模塊添加對鏈式方法支持 $(window).method1().method2().methodN()
;(function($){
//取回最初匹配到的集合 例如:$("body").children().css("border","2px solid red").end().css("border","2px solid yellow") 子元素紅邊框,body黃邊框
$.fn.end = function(){
return this.prevObject || $()
}

//把最初集合也添加到當前集合中 例如:$("body").children().andSelf().css("border","2px solid red")這樣body也會被添加邊框
$.fn.andSelf = function(){
return this.add(this.prevObject || $())
}

'filter,add,not,eq,first,last,find,closest,parents,parent,children,siblings'.split(',').forEach(function(property){
//保存上面方法原來的函數
var fn = $.fn[property]
//指向新的函數
$.fn[property] = function(){
var ret = fn.apply(this, arguments)
//保存當前對象
ret.prevObject = this
return ret
}
})
})(Zepto)

 

//這模塊用來修復低版本IOS的問題,String.prototype可能會缺失trim方法 ,Array.prototype可能會缺失 reduce()
;(function(undefined){
if (String.prototype.trim === undefined) // fix for iOS 3.2
String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, '') }

// For iOS 3.x
// from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
if (Array.prototype.reduce === undefined)
//reduce方法對遍歷數組進行累計處理,把前一個數組項返回值做爲參數傳到下一個數值項的操做中
Array.prototype.reduce = function(fun){
//這裏的void 0 是一直會返回undefined,void是不能被覆蓋的,若是直接使用undefined的話,擔憂出現undefined被覆蓋的狀況(由於它曾經是能夠被覆蓋的,非保留關鍵詞)
if(this === void 0 || this === null) throw new TypeError()
//t.length >>> 0 位運算,若是左邊有正的數值,那麼會返回這個數值,undefined,null,空等會返回0
//accumulator爲上次累計返回值
var t = Object(this), len = t.length >>> 0, k = 0, accumulator
if(typeof fun != 'function') throw new TypeError()
//若是數組長度爲0,且沒有傳遞初始值(即爲數組中第一項調用時的previousValue)
if(len == 0 && arguments.length == 1) throw new TypeError()

if(arguments.length >= 2)
//有傳入初始值,賦予accumulator初始值
accumulator = arguments[1]
else
do{
if(k in t){
//沒有傳遞初始值,拿數組第一項做爲初始值
accumulator = t[k++]
break
}
//數組長度爲1,且沒有給初始值的狀況
if(++k >= len) throw new TypeError()
} while (true)
//累計運算
while (k < len){
if(k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t)
k++
}
return accumulator
}

})()

相關文章
相關標籤/搜索