Permalink
Browse files

no one escapes the austrian inquisition

  • Loading branch information...
1 parent 0366f9a commit 68cbe1f4569948d354dcb0396131921443ac69ed @madrobby committed Mar 28, 2012
Showing with 424 additions and 684 deletions.
  1. +121 −292 src/ajax.js
  2. +9 −17 src/assets.js
  3. +12 −12 src/data.js
  4. +12 −35 src/detect.js
  5. +103 −102 src/event.js
  6. +19 −74 src/form.js
  7. +38 −38 src/fx.js
  8. +46 −46 src/fx_methods.js
  9. +16 −16 src/gesture.js
  10. +16 −16 src/polyfill.js
  11. +32 −36 src/touch.js
View
413 src/ajax.js
@@ -2,131 +2,102 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($){
+;(function($){
var jsonpID = 0,
isObject = $.isObject,
document = window.document,
key,
name,
- rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
+ rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi
// trigger a custom event and return false if it was cancelled
function triggerAndReturn(context, eventName, data) {
- var event = $.Event(eventName);
- $(context).trigger(event, data);
- return !event.defaultPrevented;
+ var event = $.Event(eventName)
+ $(context).trigger(event, data)
+ return !event.defaultPrevented
}
// trigger an Ajax "global" event
function triggerGlobal(settings, context, eventName, data) {
- if (settings.global) return triggerAndReturn(context || document, eventName, data);
+ if (settings.global) return triggerAndReturn(context || document, eventName, data)
}
// Number of active Ajax requests
- $.active = 0;
+ $.active = 0
function ajaxStart(settings) {
- if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart');
+ if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}
function ajaxStop(settings) {
- if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop');
+ 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;
+ var context = settings.context
if (settings.beforeSend.call(context, xhr, settings) === false ||
triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
- return false;
+ return false
- triggerGlobal(settings, context, 'ajaxSend', [xhr, settings]);
+ triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}
function ajaxSuccess(data, xhr, settings) {
- var context = settings.context, status = 'success';
- settings.success.call(context, data, status, xhr);
- triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data]);
- ajaxComplete(status, xhr, settings);
+ var context = settings.context, status = 'success'
+ settings.success.call(context, data, status, xhr)
+ triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
+ ajaxComplete(status, xhr, settings)
}
// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings) {
- var context = settings.context;
- settings.error.call(context, xhr, type, error);
- triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error]);
- ajaxComplete(type, xhr, settings);
+ var context = settings.context
+ settings.error.call(context, xhr, type, error)
+ triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error])
+ 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);
+ 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
- //
- // Load JSON from a server in a different domain (JSONP)
- //
- // *Arguments:*
- //
- // options — object that configure the request,
- // see avaliable options below
- //
- // *Avaliable options:*
- //
- // url — url to which the request is sent
- // success — callback that is executed if the request succeeds
- // error — callback that is executed if the server drops error
- // context — in which context to execute the callbacks in
- //
- // *Example:*
- //
- // $.ajaxJSONP({
- // url: 'http://example.com/projects?callback=?',
- // success: function (data) {
- // projects.push(json);
- // }
- // });
- //
$.ajaxJSONP = function(options){
var callbackName = 'jsonp' + (++jsonpID),
script = document.createElement('script'),
abort = function(){
- $(script).remove();
- if (callbackName in window) window[callbackName] = empty;
- ajaxComplete('abort', xhr, options);
+ $(script).remove()
+ if (callbackName in window) window[callbackName] = empty
+ ajaxComplete('abort', xhr, options)
},
- xhr = { abort: abort }, abortTimeout;
+ xhr = { abort: abort }, abortTimeout
if (options.error) script.onerror = function() {
- xhr.abort();
- options.error();
- };
+ xhr.abort()
+ options.error()
+ }
window[callbackName] = function(data){
- clearTimeout(abortTimeout);
- $(script).remove();
- delete window[callbackName];
- ajaxSuccess(data, xhr, options);
- };
+ clearTimeout(abortTimeout)
+ $(script).remove()
+ delete window[callbackName]
+ ajaxSuccess(data, xhr, options)
+ }
- script.src = options.url.replace(/=\?/, '=' + callbackName);
- $('head').append(script);
+ script.src = options.url.replace(/=\?/, '=' + callbackName)
+ $('head').append(script)
if (options.timeout > 0) abortTimeout = setTimeout(function(){
- xhr.abort();
- ajaxComplete('timeout', xhr, options);
- }, options.timeout);
+ xhr.abort()
+ ajaxComplete('timeout', xhr, options)
+ }, options.timeout)
- return xhr;
- };
+ return xhr
+ }
- // ### $.ajaxSettings
- //
- // AJAX settings
- //
$.ajaxSettings = {
// Default type of request
type: 'GET',
@@ -144,7 +115,7 @@
global: true,
// Transport
xhr: function () {
- return new window.XMLHttpRequest();
+ return new window.XMLHttpRequest()
},
// MIME types mapping
accepts: {
@@ -158,268 +129,126 @@
crossDomain: false,
// Default timeout
timeout: 0
- };
-
- // ### $.ajax
- //
- // Perform AJAX request
- //
- // *Arguments:*
- //
- // options — object that configure the request,
- // see avaliable options below
- //
- // *Avaliable options:*
- //
- // type ('GET') — type of request GET / POST
- // url (window.location) — url to which the request is sent
- // data — data to send to server,
- // can be string or object
- // dataType ('json') — what response type you accept from
- // the server:
- // 'json', 'xml', 'html', or 'text'
- // timeout (0) — request timeout
- // beforeSend — callback that is executed before
- // request send
- // complete — callback that is executed on request
- // complete (both: error and success)
- // success — callback that is executed if
- // the request succeeds
- // error — callback that is executed if
- // the server drops error
- // context — in which context to execute the
- // callbacks in
- //
- // *Example:*
- //
- // $.ajax({
- // type: 'POST',
- // url: '/projects',
- // data: { name: 'Zepto.js' },
- // dataType: 'html',
- // timeout: 100,
- // context: $('body'),
- // success: function (data) {
- // this.append(data);
- // },
- // error: function (xhr, type) {
- // alert('Error!');
- // }
- // });
- //
+ }
+
$.ajax = function(options){
- var settings = $.extend({}, options || {});
- for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key];
+ var settings = $.extend({}, options || {})
+ for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]
- ajaxStart(settings);
+ ajaxStart(settings)
if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
- RegExp.$2 != window.location.host;
+ RegExp.$2 != window.location.host
- if (/=\?/.test(settings.url)) return $.ajaxJSONP(settings);
+ if (/=\?/.test(settings.url)) return $.ajaxJSONP(settings)
- if (!settings.url) settings.url = window.location.toString();
- if (settings.data && !settings.contentType) settings.contentType = 'application/x-www-form-urlencoded';
- if (isObject(settings.data)) settings.data = $.param(settings.data);
+ if (!settings.url) settings.url = window.location.toString()
+ if (settings.data && !settings.contentType) settings.contentType = 'application/x-www-form-urlencoded'
+ if (isObject(settings.data)) settings.data = $.param(settings.data)
if (settings.type.match(/get/i) && settings.data) {
- var queryString = settings.data;
- if (settings.url.match(/\?.*=/)) {
- queryString = '&' + queryString;
- } else if (queryString[0] != '?') {
- queryString = '?' + queryString;
- }
- settings.url += queryString;
+ var queryString = settings.data
+ if (settings.url.match(/\?.*=/))
+ queryString = '&' + queryString
+ else if (queryString[0] != '?')
+ queryString = '?' + queryString
+
+ settings.url += queryString
}
var mime = settings.accepts[settings.dataType],
baseHeaders = { },
protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
- xhr = $.ajaxSettings.xhr(), abortTimeout;
+ xhr = $.ajaxSettings.xhr(), abortTimeout
- if (!settings.crossDomain) baseHeaders['X-Requested-With'] = 'XMLHttpRequest';
- if (mime) baseHeaders['Accept'] = mime;
- settings.headers = $.extend(baseHeaders, settings.headers || {});
+ if (!settings.crossDomain) baseHeaders['X-Requested-With'] = 'XMLHttpRequest'
+ if (mime) baseHeaders['Accept'] = mime
+ settings.headers = $.extend(baseHeaders, settings.headers || {})
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
- clearTimeout(abortTimeout);
- var result, error = false;
+ clearTimeout(abortTimeout)
+ var result, error = false
if ((xhr.status >= 200 && xhr.status < 300) || (xhr.status == 0 && protocol == 'file:')) {
if (mime == 'application/json' && !(/^\s*$/.test(xhr.responseText))) {
- try { result = JSON.parse(xhr.responseText); }
- catch (e) { error = e; }
+ try { result = JSON.parse(xhr.responseText) }
+ catch (e) { error = e }
}
- else result = xhr.responseText;
- if (error) ajaxError(error, 'parsererror', xhr, settings);
- else ajaxSuccess(result, xhr, settings);
+ else result = xhr.responseText
+ if (error)
+ ajaxError(error, 'parsererror', xhr, settings)
+ else
+ ajaxSuccess(result, xhr, settings)
} else {
- ajaxError(null, 'error', xhr, settings);
+ ajaxError(null, 'error', xhr, settings)
}
}
- };
+ }
- var async = 'async' in settings ? settings.async : true;
- xhr.open(settings.type, settings.url, async);
+ var async = 'async' in settings ? settings.async : true
+ xhr.open(settings.type, settings.url, async)
- if (settings.contentType) settings.headers['Content-Type'] = settings.contentType;
- for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name]);
+ if (settings.contentType) settings.headers['Content-Type'] = settings.contentType
+ for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name])
if (ajaxBeforeSend(xhr, settings) === false) {
- xhr.abort();
- return false;
+ xhr.abort()
+ return false
}
if (settings.timeout > 0) abortTimeout = setTimeout(function(){
- xhr.onreadystatechange = empty;
- xhr.abort();
- ajaxError(null, 'timeout', xhr, settings);
- }, settings.timeout);
-
- xhr.send(settings.data);
- return xhr;
- };
-
- // ### $.get
- //
- // Load data from the server using a GET request
- //
- // *Arguments:*
- //
- // url — url to which the request is sent
- // success — callback that is executed if the request succeeds
- //
- // *Example:*
- //
- // $.get(
- // '/projects/42',
- // function (data) {
- // $('body').append(data);
- // }
- // );
- //
- $.get = function(url, success){ return $.ajax({ url: url, success: success }) };
-
- // ### $.post
- //
- // Load data from the server using POST request
- //
- // *Arguments:*
- //
- // url — url to which the request is sent
- // [data] — data to send to server, can be string or object
- // [success] — callback that is executed if the request succeeds
- // [dataType] — type of expected response
- // 'json', 'xml', 'html', or 'text'
- //
- // *Example:*
- //
- // $.post(
- // '/projects',
- // { name: 'Zepto.js' },
- // function (data) {
- // $('body').append(data);
- // },
- // 'html'
- // );
- //
+ xhr.onreadystatechange = empty
+ xhr.abort()
+ ajaxError(null, 'timeout', xhr, settings)
+ }, settings.timeout)
+
+ xhr.send(settings.data)
+ return xhr
+ }
+
+ $.get = function(url, success){ return $.ajax({ url: url, success: success }) }
+
$.post = function(url, data, success, dataType){
- if ($.isFunction(data)) dataType = dataType || success, success = data, data = null;
- return $.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType });
- };
-
- // ### $.getJSON
- //
- // Load JSON from the server using GET request
- //
- // *Arguments:*
- //
- // url — url to which the request is sent
- // success — callback that is executed if the request succeeds
- //
- // *Example:*
- //
- // $.getJSON(
- // '/projects/42',
- // function (json) {
- // projects.push(json);
- // }
- // );
- //
+ if ($.isFunction(data)) dataType = dataType || success, success = data, data = null
+ return $.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType })
+ }
+
$.getJSON = function(url, success){
- return $.ajax({ url: url, success: success, dataType: 'json' });
- };
-
- // ### $.fn.load
- //
- // Load data from the server into an element
- //
- // *Arguments:*
- //
- // url — url to which the request is sent
- // [success] — callback that is executed if the request succeeds
- //
- // *Examples:*
- //
- // $('#project_container').get(
- // '/projects/42',
- // function () {
- // alert('Project was successfully loaded');
- // }
- // );
- //
- // $('#project_comments').get(
- // '/projects/42 #comments',
- // function () {
- // alert('Comments was successfully loaded');
- // }
- // );
- //
+ return $.ajax({ url: url, success: success, dataType: 'json' })
+ }
+
$.fn.load = function(url, success){
- if (!this.length) return this;
- var self = this, parts = url.split(/\s/), selector;
- if (parts.length > 1) url = parts[0], selector = parts[1];
+ if (!this.length) return this
+ var self = this, parts = url.split(/\s/), selector
+ if (parts.length > 1) url = parts[0], selector = parts[1]
$.get(url, function(response){
self.html(selector ?
$(document.createElement('div')).html(response.replace(rscript, "")).find(selector).html()
- : response);
- success && success.call(self);
- });
- return this;
- };
+ : response)
+ success && success.call(self)
+ })
+ return this
+ }
- var escape = encodeURIComponent;
+ var escape = encodeURIComponent
function serialize(params, obj, traditional, scope){
- var array = $.isArray(obj);
+ var array = $.isArray(obj)
$.each(obj, function(key, value) {
- if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']';
+ if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
// handle data in serializeArray() format
- if (!scope && array) params.add(value.name, value.value);
+ if (!scope && array) params.add(value.name, value.value)
// recurse into nested objects
else if (traditional ? $.isArray(value) : isObject(value))
- serialize(params, value, traditional, key);
- else params.add(key, value);
- });
+ serialize(params, value, traditional, key)
+ else params.add(key, value)
+ })
}
- // ### $.param
- //
- // Encode object as a string of URL-encoded key-value pairs
- //
- // *Arguments:*
- //
- // obj — object to serialize
- // [traditional] — perform shallow serialization
- //
- // *Example:*
- //
- // $.param( { name: 'Zepto.js', version: '0.6' } );
- //
$.param = function(obj, traditional){
- var params = [];
- params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) };
- serialize(params, obj, traditional);
- return params.join('&').replace('%20', '+');
- };
-})(Zepto);
+ var params = []
+ params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
+ serialize(params, obj, traditional)
+ return params.join('&').replace('%20', '+')
+ }
+})(Zepto)
View
26 src/assets.js
@@ -2,28 +2,20 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($){
- var cache = [], timeout;
+;(function($){
+ var cache = [], timeout
- // ### $.fn.remove
- //
- // Remove element from DOM
- //
- // *Example:*
- //
- // $('#projects, .comments').remove();
- //
$.fn.remove = function(){
return this.each(function(){
if(this.parentNode){
if(this.tagName === 'IMG'){
- cache.push(this);
- this.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
- if (timeout) clearTimeout(timeout);
- timeout = setTimeout(function(){ cache = [] }, 60000);
+ cache.push(this)
+ this.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
+ if (timeout) clearTimeout(timeout)
+ timeout = setTimeout(function(){ cache = [] }, 60000)
}
- this.parentNode.removeChild(this);
+ this.parentNode.removeChild(this)
}
- });
+ })
}
-})(Zepto);
+})(Zepto)
View
24 src/data.js
@@ -4,30 +4,30 @@
// The following code is heavily inspired by jQuery's $.fn.data()
-(function($) {
+;(function($) {
var data = {}, dataAttr = $.fn.data,
uuid = $.uuid = +new Date(),
- exp = $.expando = 'Zepto' + uuid;
+ exp = $.expando = 'Zepto' + uuid
function getData(node, name) {
- var id = node[exp], store = id && data[id];
+ var id = node[exp], store = id && data[id]
return name === undefined ? store || setData(node) :
- (store && store[name]) || dataAttr.call($(node), name);
+ (store && store[name]) || dataAttr.call($(node), name)
}
function setData(node, name, value) {
var id = node[exp] || (node[exp] = ++uuid),
- store = data[id] || (data[id] = {});
- if (name !== undefined) store[name] = value;
- return store;
- };
+ store = data[id] || (data[id] = {})
+ if (name !== undefined) store[name] = value
+ return store
+ }
$.fn.data = function(name, value) {
return value === undefined ?
this.length == 0 ? undefined : getData(this[0], name) :
this.each(function(idx){
setData(this, name, $.isFunction(value) ?
- value.call(this, idx, getData(this, name)) : value);
- });
- };
-})(Zepto);
+ value.call(this, idx, getData(this, name)) : value)
+ })
+ }
+})(Zepto)
View
47 src/detect.js
@@ -2,7 +2,7 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($){
+;(function($){
function detect(ua){
var os = this.os = {}, browser = this.browser = {},
webkit = ua.match(/WebKit\/([\d.]+)/),
@@ -11,43 +11,20 @@
iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),
touchpad = webos && ua.match(/TouchPad/),
- blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
+ blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/)
- if (browser.webkit = !!webkit) browser.version = webkit[1];
+ if (browser.webkit = !!webkit) browser.version = webkit[1]
- if (android) os.android = true, os.version = android[2];
- if (iphone) 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 (webos) os.webos = true, os.version = webos[2];
- if (touchpad) os.touchpad = true;
- if (blackberry) os.blackberry = true, os.version = blackberry[2];
+ if (android) os.android = true, os.version = android[2]
+ if (iphone) 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 (webos) os.webos = true, os.version = webos[2]
+ if (touchpad) os.touchpad = true
+ if (blackberry) os.blackberry = true, os.version = blackberry[2]
}
- // ### $.os
- //
- // Object containing information about browser platform
- //
- // *Example:*
- //
- // $.os.ios // => true if running on Apple iOS
- // $.os.android // => true if running on Android
- // $.os.webos // => true if running on HP/Palm WebOS
- // $.os.touchpad // => true if running on a HP TouchPad
- // $.os.version // => string with a version number, e.g.
- // "4.0", "3.1.1", "2.1", etc.
- // $.os.iphone // => true if running on iPhone
- // $.os.ipad // => true if running on iPad
- // $.os.blackberry // => true if running on BlackBerry
- //
- // ### $.browser
- //
- // *Example:*
- //
- // $.browser.webkit // => true if the browser is WebKit-based
- // $.browser.version // => WebKit version string
- detect.call($, navigator.userAgent);
-
+ detect.call($, navigator.userAgent)
// make available to unit tests
- $.__detect = detect;
+ $.__detect = detect
-})(Zepto);
+})(Zepto)
View
205 src/event.js
@@ -2,206 +2,207 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($){
- var $$ = $.qsa, handlers = {}, _zid = 1, specialEvents={};
+;(function($){
+ var $$ = $.qsa, handlers = {}, _zid = 1, specialEvents={}
- specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents';
+ specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
function zid(element) {
- return element._zid || (element._zid = _zid++);
+ return element._zid || (element._zid = _zid++)
}
function findHandlers(element, event, fn, selector) {
- event = parse(event);
- if (event.ns) var matcher = matcherFor(event.ns);
+ event = parse(event)
+ if (event.ns) var matcher = matcherFor(event.ns)
return (handlers[zid(element)] || []).filter(function(handler) {
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || handler.fn == fn)
- && (!selector || handler.sel == selector);
- });
+ && (!selector || handler.sel == selector)
+ })
}
function parse(event) {
- var parts = ('' + event).split('.');
- return {e: parts[0], ns: parts.slice(1).sort().join(' ')};
+ var parts = ('' + event).split('.')
+ return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}
function matcherFor(ns) {
- return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)');
+ return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}
function eachEvent(events, fn, iterator){
- if ($.isObject(events)) $.each(events, iterator);
- else events.split(/\s/).forEach(function(type){ iterator(type, fn) });
+ if ($.isObject(events)) $.each(events, iterator)
+ else events.split(/\s/).forEach(function(type){ iterator(type, fn) })
}
function add(element, events, fn, selector, getDelegate, capture){
- capture = !!capture;
- var id = zid(element), set = (handlers[id] || (handlers[id] = []));
+ capture = !!capture
+ var id = zid(element), set = (handlers[id] || (handlers[id] = []))
eachEvent(events, fn, function(event, fn){
var delegate = getDelegate && getDelegate(fn, event),
- callback = delegate || fn;
+ callback = delegate || fn
var proxyfn = function (event) {
- var result = callback.apply(element, [event].concat(event.data));
- if (result === false) event.preventDefault();
- return result;
- };
- var handler = $.extend(parse(event), {fn: fn, proxy: proxyfn, sel: selector, del: delegate, i: set.length});
- set.push(handler);
- element.addEventListener(handler.e, proxyfn, capture);
- });
+ var result = callback.apply(element, [event].concat(event.data))
+ if (result === false) event.preventDefault()
+ return result
+ }
+ var handler = $.extend(parse(event), {fn: fn, proxy: proxyfn, sel: selector, del: delegate, i: set.length})
+ set.push(handler)
+ element.addEventListener(handler.e, proxyfn, capture)
+ })
}
function remove(element, events, fn, selector){
- var id = zid(element);
+ var id = zid(element)
eachEvent(events || '', fn, function(event, fn){
findHandlers(element, event, fn, selector).forEach(function(handler){
- delete handlers[id][handler.i];
- element.removeEventListener(handler.e, handler.proxy, false);
- });
- });
+ delete handlers[id][handler.i]
+ element.removeEventListener(handler.e, handler.proxy, false)
+ })
+ })
}
$.event = { add: add, remove: remove }
$.fn.bind = function(event, callback){
return this.each(function(){
- add(this, event, callback);
- });
- };
+ add(this, event, callback)
+ })
+ }
$.fn.unbind = function(event, callback){
return this.each(function(){
- remove(this, event, callback);
- });
- };
+ remove(this, event, callback)
+ })
+ }
$.fn.one = function(event, callback){
return this.each(function(i, element){
add(this, event, callback, null, function(fn, type){
return function(){
- var result = fn.apply(element, arguments);
- remove(element, type, fn);
- return result;
+ var result = fn.apply(element, arguments)
+ remove(element, type, fn)
+ return result
}
- });
- });
- };
+ })
+ })
+ }
var returnTrue = function(){return true},
returnFalse = function(){return false},
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
- };
+ }
function createProxy(event) {
- var proxy = $.extend({originalEvent: event}, event);
+ var proxy = $.extend({originalEvent: event}, event)
$.each(eventMethods, function(name, predicate) {
proxy[name] = function(){
- this[predicate] = returnTrue;
- return event[name].apply(event, arguments);
- };
- proxy[predicate] = returnFalse;
+ this[predicate] = returnTrue
+ return event[name].apply(event, arguments)
+ }
+ proxy[predicate] = returnFalse
})
- return proxy;
+ return proxy
}
// emulates the 'defaultPrevented' property for browsers that have none
function fix(event) {
if (!('defaultPrevented' in event)) {
- event.defaultPrevented = false;
- var prevent = event.preventDefault;
+ event.defaultPrevented = false
+ var prevent = event.preventDefault
event.preventDefault = function() {
- this.defaultPrevented = true;
- prevent.call(this);
+ this.defaultPrevented = true
+ prevent.call(this)
}
}
}
$.fn.delegate = function(selector, event, callback){
- var capture = false;
+ var capture = false
if(event == 'blur' || event == 'focus'){
if($.iswebkit)
- event = event == 'blur' ? 'focusout' : event == 'focus' ? 'focusin' : event;
+ event = event == 'blur' ? 'focusout' : event == 'focus' ? 'focusin' : event
else
- capture = true;
+ capture = true
}
return this.each(function(i, element){
add(element, event, callback, selector, function(fn){
return function(e){
- var evt, match = $(e.target).closest(selector, element).get(0);
+ var evt, match = $(e.target).closest(selector, element).get(0)
if (match) {
- evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element});
- return fn.apply(match, [evt].concat([].slice.call(arguments, 1)));
+ evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
+ return fn.apply(match, [evt].concat([].slice.call(arguments, 1)))
}
}
- }, capture);
- });
- };
+ }, capture)
+ })
+ }
$.fn.undelegate = function(selector, event, callback){
return this.each(function(){
- remove(this, event, callback, selector);
- });
+ remove(this, event, callback, selector)
+ })
}
$.fn.live = function(event, callback){
- $(document.body).delegate(this.selector, event, callback);
- return this;
- };
+ $(document.body).delegate(this.selector, event, callback)
+ return this
+ }
$.fn.die = function(event, callback){
- $(document.body).undelegate(this.selector, event, callback);
- return this;
- };
+ $(document.body).undelegate(this.selector, event, callback)
+ return this
+ }
$.fn.on = function(event, selector, callback){
return selector === undefined || $.isFunction(selector) ?
- this.bind(event, selector) : this.delegate(selector, event, callback);
- };
+ this.bind(event, selector) : this.delegate(selector, event, callback)
+ }
$.fn.off = function(event, selector, callback){
return selector === undefined || $.isFunction(selector) ?
- this.unbind(event, selector) : this.undelegate(selector, event, callback);
- };
+ this.unbind(event, selector) : this.undelegate(selector, event, callback)
+ }
$.fn.trigger = function(event, data){
- if (typeof event == 'string') event = $.Event(event);
- fix(event);
- event.data = data;
- return this.each(function(){ this.dispatchEvent(event) });
- };
+ if (typeof event == 'string') event = $.Event(event)
+ fix(event)
+ event.data = data
+ return this.each(function(){ this.dispatchEvent(event) })
+ }
// 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, data){
- var e, result;
+ var e, result
this.each(function(i, element){
- e = createProxy(typeof event == 'string' ? $.Event(event) : event);
- e.data = data; e.target = element;
+ e = createProxy(typeof event == 'string' ? $.Event(event) : event)
+ e.data = data
+ e.target = element
$.each(findHandlers(element, event.type || event), function(i, handler){
- result = handler.proxy(e);
- if (e.isImmediatePropagationStopped()) return false;
- });
- });
- return result;
- };
+ 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 '+
+ ;('focusin focusout load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
- $.fn[event] = function(callback){ return this.bind(event, callback) };
- });
+ $.fn[event] = function(callback){ return this.bind(event, callback) }
+ })
- ['focus', 'blur'].forEach(function(name) {
+ ;['focus', 'blur'].forEach(function(name) {
$.fn[name] = function(callback) {
- if (callback) this.bind(name, callback);
- else if (this.length) try { this.get(0)[name]() } catch(e){};
- return this;
- };
- });
+ if (callback) this.bind(name, callback)
+ else if (this.length) try { this.get(0)[name]() } catch(e){}
+ return this
+ }
+ })
$.Event = function(type, props) {
- var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true;
- if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]);
- event.initEvent(type, bubbles, true, null, null, null, null, null, null, null, null, null, null, null, null);
- return event;
- };
+ var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
+ if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
+ event.initEvent(type, bubbles, true, null, null, null, null, null, null, null, null, null, null, null, null)
+ return event
+ }
-})(Zepto);
+})(Zepto)
View
93 src/form.js
@@ -2,94 +2,39 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function ($) {
-
- // ### $.fn.serializeArray
- //
- // Encode a set of form elements as an array of names and values
- //
- // *Example:*
- //
- // $('#login_form').serializeArray();
- //
- // returns
- //
- // [
- // {
- // name: 'email',
- // value: 'koss@nocorp.me'
- // },
- // {
- // name: 'password',
- // value: '123456'
- // }
- // ]
- //
+;(function ($) {
$.fn.serializeArray = function () {
- var result = [], el;
+ var result = [], el
$( Array.prototype.slice.call(this.get(0).elements) ).each(function () {
- el = $(this);
- var type = el.attr('type');
- if (
- this.nodeName.toLowerCase() != 'fieldset' &&
+ el = $(this)
+ var type = el.attr('type')
+ if (this.nodeName.toLowerCase() != 'fieldset' &&
!this.disabled && type != 'submit' && type != 'reset' && type != 'button' &&
- ((type != 'radio' && type != 'checkbox') || this.checked)
- ) {
+ ((type != 'radio' && type != 'checkbox') || this.checked))
result.push({
name: el.attr('name'),
value: el.val()
- });
- }
- });
- return result;
- };
+ })
+ })
+ return result
+ }
- // ### $.fn.serialize
- //
- //
- // Encode a set of form elements as a string for submission
- //
- // *Example:*
- //
- // $('#login_form').serialize();
- //
- // returns
- //
- // "email=koss%40nocorp.me&password=123456"
- //
$.fn.serialize = function () {
- var result = [];
+ var result = []
this.serializeArray().forEach(function (elm) {
- result.push( encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value) );
- });
- return result.join('&');
- };
+ result.push( encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value) )
+ })
+ return result.join('&')
+ }
- // ### $.fn.submit
- //
- // Bind or trigger the submit event for a form
- //
- // *Examples:*
- //
- // To bind a handler for the submit event:
- //
- // $('#login_form').submit(function (e) {
- // alert('Form was submitted!');
- // e.preventDefault();
- // });
- //
- // To trigger form submit:
- //
- // $('#login_form').submit();
- //
$.fn.submit = function (callback) {
if (callback) this.bind('submit', callback)
else if (this.length) {
- var event = $.Event('submit');
- this.eq(0).trigger(event);
+ var event = $.Event('submit')
+ this.eq(0).trigger(event)
if (!event.defaultPrevented) this.get(0).submit()
}
- return this;
+ return this
}
-})(Zepto);
+})(Zepto)
View
76 src/fx.js
@@ -2,81 +2,81 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($, undefined){
+;(function($, undefined){
var prefix = '', eventPrefix, endEventName, endAnimationName,
vendors = {Webkit: 'webkit', Moz: '', O: 'o', ms: 'MS'},
document = window.document, testEl = document.createElement('div'),
- supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i;
+ supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i
function downcase(str) { return str.toLowerCase() }
- function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : downcase(name) };
+ function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : downcase(name) }
$.each(vendors, function(vendor, event){
if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
- prefix = '-' + downcase(vendor) + '-';
- eventPrefix = event;
- return false;
+ prefix = '-' + downcase(vendor) + '-'
+ eventPrefix = event
+ return false
}
- });
+ })
$.fx = {
off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
cssPrefix: prefix,
transitionEnd: normalizeEvent('TransitionEnd'),
animationEnd: normalizeEvent('AnimationEnd')
- };
+ }
$.fn.animate = function(properties, duration, ease, callback){
if ($.isObject(duration))
- ease = duration.easing, callback = duration.complete, duration = duration.duration;
- if (duration) duration = duration / 1000;
- return this.anim(properties, duration, ease, callback);
- };
+ ease = duration.easing, callback = duration.complete, duration = duration.duration
+ if (duration) duration = duration / 1000
+ return this.anim(properties, duration, ease, callback)
+ }
$.fn.anim = function(properties, duration, ease, callback){
- var transforms, cssProperties = {}, key, that = this, wrappedCallback, endEvent = $.fx.transitionEnd;
- if (duration === undefined) duration = 0.4;
- if ($.fx.off) duration = 0;
+ var transforms, cssProperties = {}, key, that = this, wrappedCallback, endEvent = $.fx.transitionEnd
+ if (duration === undefined) duration = 0.4
+ if ($.fx.off) duration = 0
if (typeof properties == 'string') {
// keyframe animation
- cssProperties[prefix + 'animation-name'] = properties;
- cssProperties[prefix + 'animation-duration'] = duration + 's';
- endEvent = $.fx.animationEnd;
+ cssProperties[prefix + 'animation-name'] = properties
+ cssProperties[prefix + 'animation-duration'] = duration + 's'
+ endEvent = $.fx.animationEnd
} else {
// CSS transitions
for (key in properties)
if (supportedTransforms.test(key)) {
- transforms || (transforms = []);
- transforms.push(key + '(' + properties[key] + ')');
+ transforms || (transforms = [])
+ transforms.push(key + '(' + properties[key] + ')')
}
- else cssProperties[key] = properties[key];
+ else cssProperties[key] = properties[key]
- if (transforms) cssProperties[prefix + 'transform'] = transforms.join(' ');
- if (!$.fx.off) cssProperties[prefix + 'transition'] = 'all ' + duration + 's ' + (ease || '');
+ if (transforms) cssProperties[prefix + 'transform'] = transforms.join(' ')
+ if (!$.fx.off) cssProperties[prefix + 'transition'] = 'all ' + duration + 's ' + (ease || '')
}
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, arguments.callee);
+ if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
+ $(event.target).unbind(endEvent, arguments.callee)
}
- var props = {};
- props[prefix + 'transition'] = props[prefix + 'animation-name'] = 'none';
- $(this).css(props);
- callback && callback.call(this);
+ var props = {}
+ props[prefix + 'transition'] = props[prefix + 'animation-name'] = 'none'
+ $(this).css(props)
+ callback && callback.call(this)
}
- if (duration > 0) this.bind(endEvent, wrappedCallback);
+ if (duration > 0) this.bind(endEvent, wrappedCallback)
setTimeout(function() {
- that.css(cssProperties);
+ that.css(cssProperties)
if (duration <= 0) setTimeout(function() {
- that.each(function(){ wrappedCallback.call(this) });
- }, 0);
- }, 0);
+ that.each(function(){ wrappedCallback.call(this) })
+ }, 0)
+ }, 0)
- return this;
- };
+ return this
+ }
- testEl = null;
-})(Zepto);
+ testEl = null
+})(Zepto)
View
92 src/fx_methods.js
@@ -2,97 +2,97 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($, undefined){
+;(function($, undefined){
var document = window.document, docElem = document.documentElement,
origShow = $.fn.show, origHide = $.fn.hide, origToggle = $.fn.toggle,
- speeds = { _default: 400, fast: 200, slow: 600 };
+ speeds = { _default: 400, fast: 200, slow: 600 }
function translateSpeed(speed) {
- return typeof speed == 'number' ? speed : (speeds[speed] || speeds._default);
+ return typeof speed == 'number' ? speed : (speeds[speed] || speeds._default)
}
function anim(el, speed, opacity, scale, callback) {
- if (typeof speed == 'function' && !callback) callback = speed, speed = undefined;
- var props = { opacity: opacity };
+ if (typeof speed == 'function' && !callback) callback = speed, speed = undefined
+ var props = { opacity: opacity }
if (scale) {
- if ($.fx.transforms3d) props.scale3d = scale + ',1';
- else props.scale = scale;
- el.css($.fx.cssPrefix + 'transform-origin', '0 0');
+ if ($.fx.transforms3d) props.scale3d = scale + ',1'
+ else props.scale = scale
+ el.css($.fx.cssPrefix + 'transform-origin', '0 0')
}
- return el.anim(props, translateSpeed(speed) / 1000, null, callback);
+ return el.anim(props, translateSpeed(speed) / 1000, null, callback)
}
function hide(el, speed, scale, callback) {
return anim(el, speed, 0, scale, function(){
- origHide.call($(this));
- callback && callback.call(this);
- });
+ origHide.call($(this))
+ callback && callback.call(this)
+ })
}
$.fn.show = function(speed, callback) {
- origShow.call(this);
- if (speed === undefined) speed = 0;
- else this.css('opacity', 0);
- return anim(this, speed, 1, '1,1', callback);
- };
+ origShow.call(this)
+ if (speed === undefined) speed = 0
+ else this.css('opacity', 0)
+ return anim(this, speed, 1, '1,1', callback)
+ }
$.fn.hide = function(speed, callback) {
- if (speed === undefined) return origHide.call(this);
- else return hide(this, speed, '0,0', callback);
+ if (speed === undefined) return origHide.call(this)
+ else return hide(this, speed, '0,0', callback)
}
$.fn.toggle = function(speed, callback) {
- if (speed === undefined || typeof speed == 'boolean') return origToggle.call(this, speed);
- else return this[this.css('display') == 'none' ? 'show' : 'hide'](speed, callback);
- };
+ if (speed === undefined || typeof speed == 'boolean') return origToggle.call(this, speed)
+ else return this[this.css('display') == 'none' ? 'show' : 'hide'](speed, callback)
+ }
$.fn.fadeTo = function(speed, opacity, callback) {
- return anim(this, speed, opacity, null, callback);
- };
+ return anim(this, speed, opacity, null, callback)
+ }
$.fn.fadeIn = function(speed, callback) {
var target = this.css('opacity')
if (target > 0) this.css('opacity', 0)
else target = 1
- return origShow.call(this).fadeTo(speed, target, callback);
- };
+ return origShow.call(this).fadeTo(speed, target, callback)
+ }
$.fn.fadeOut = function(speed, callback) {
- return hide(this, speed, null, callback);
- };
+ return hide(this, speed, null, callback)
+ }
$.fn.fadeToggle = function(speed, callback) {
- var hidden = this.css('opacity') == 0 || this.css('display') == 'none';
- return this[hidden ? 'fadeIn' : 'fadeOut'](speed, callback);
- };
+ var hidden = this.css('opacity') == 0 || this.css('display') == 'none'
+ return this[hidden ? 'fadeIn' : 'fadeOut'](speed, callback)
+ }
$.extend($.fx, {
speeds: speeds,
// feature detection for 3D transforms adapted from Modernizr
transforms3d: (function(props){
- var ret = false;
+ var ret = false
$.each(props, function(i, prop){
if (docElem.style[prop] !== undefined) {
- ret = i != 1 || webkitTransforms3d();
- return false;
+ ret = i != 1 || webkitTransforms3d()
+ return false
}
- });
- return ret;
+ })
+ return ret
})('perspectiveProperty WebkitPerspective MozPerspective OPerspective msPerspective'.split(' '))
- });
+ })
function webkitTransforms3d() {
var ret, div = document.createElement('div'),
testEl = document.createElement('div'),
css = '@media (-webkit-transform-3d){#zeptotest{left:9px;position:absolute}}',
- style = ['&shy;', '<style>', css, '</style>'].join('');
+ style = ['&shy;', '<style>', css, '</style>'].join('')
- div.innerHTML += style;
- testEl.id = 'zeptotest';
- div.appendChild(testEl);
- docElem.appendChild(div);
- ret = testEl.offsetLeft === 9;
- div.parentNode.removeChild(div);
- return ret;
+ div.innerHTML += style
+ testEl.id = 'zeptotest'
+ div.appendChild(testEl)
+ docElem.appendChild(div)
+ ret = testEl.offsetLeft === 9
+ div.parentNode.removeChild(div)
+ return ret
}
-})(Zepto);
+})(Zepto)
View
32 src/gesture.js
@@ -2,34 +2,34 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($){
+;(function($){
if ($.os.ios) {
- var gesture = {}, gestureTimeout;
+ var gesture = {}, gestureTimeout
function parentIfText(node){
- return 'tagName' in node ? node : node.parentNode;
+ 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;
+ 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;
+ 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;
+ $(gesture.target).trigger('pinch' + (gesture.e1 - gesture.e2 > 0 ? 'In' : 'Out'))
+ gesture.e1 = gesture.e2 = gesture.last = 0
} else if ('last' in gesture) {
- gesture = {};
+ gesture = {}
}
- });
+ })
- ['pinch', 'pinchIn', 'pinchOut'].forEach(function(m){
+ ;['pinch', 'pinchIn', 'pinchOut'].forEach(function(m){
$.fn[m] = function(callback){ return this.bind(m, callback) }
- });
+ })
}
-})(Zepto);
+})(Zepto)
View
32 src/polyfill.js
@@ -2,35 +2,35 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function(undefined){
+;(function(undefined){
if (String.prototype.trim === undefined) // fix for iOS 3.2
- String.prototype.trim = function(){ return this.replace(/^\s+/, '').replace(/\s+$/, '') };
+ String.prototype.trim = function(){ return this.replace(/^\s+/, '').replace(/\s+$/, '') }
// For iOS 3.x
// from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
if (Array.prototype.reduce === undefined)
Array.prototype.reduce = function(fun){
- if(this === void 0 || this === null) throw new TypeError();
- var t = Object(this), len = t.length >>> 0, k = 0, accumulator;
- if(typeof fun != 'function') throw new TypeError();
- if(len == 0 && arguments.length == 1) throw new TypeError();
+ if(this === void 0 || this === null) throw new TypeError()
+ var t = Object(this), len = t.length >>> 0, k = 0, accumulator
+ if(typeof fun != 'function') throw new TypeError()
+ if(len == 0 && arguments.length == 1) throw new TypeError()
if(arguments.length >= 2)
- accumulator = arguments[1];
+ accumulator = arguments[1]
else
do{
if(k in t){
- accumulator = t[k++];
- break;
+ accumulator = t[k++]
+ break
}
- if(++k >= len) throw new TypeError();
- } while (true);
+ 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++;
+ if(k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t)
+ k++
}
- return accumulator;
- };
+ return accumulator
+ }
-})();
+})()
View
68 src/touch.js
@@ -2,65 +2,61 @@
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
-(function($){
- var touch = {}, touchTimeout;
+;(function($){
+ var touch = {}, touchTimeout
function parentIfText(node){
- return 'tagName' in node ? node : node.parentNode;
+ return 'tagName' in node ? node : node.parentNode
}
function swipeDirection(x1, x2, y1, y2){
- var xDelta = Math.abs(x1 - x2), yDelta = Math.abs(y1 - y2);
- if (xDelta >= yDelta) {
- return (x1 - x2 > 0 ? 'Left' : 'Right');
- } else {
- return (y1 - y2 > 0 ? 'Up' : 'Down');
- }
+ var xDelta = Math.abs(x1 - x2), yDelta = Math.abs(y1 - y2)
+ return xDelta >= yDelta ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}
- var longTapDelay = 750;
+ var longTapDelay = 750
function longTap(){
if (touch.last && (Date.now() - touch.last >= longTapDelay)) {
- touch.el.trigger('longTap');
- touch = {};
+ touch.el.trigger('longTap')
+ touch = {}
}
}
$(document).ready(function(){
$(document.body).bind('touchstart', function(e){
- var now = Date.now(), delta = now - (touch.last || now);
- touch.el = $(parentIfText(e.touches[0].target));
- touchTimeout && clearTimeout(touchTimeout);
- touch.x1 = e.touches[0].pageX;
- touch.y1 = e.touches[0].pageY;
- if (delta > 0 && delta <= 250) touch.isDoubleTap = true;
- touch.last = now;
- setTimeout(longTap, longTapDelay);
+ var now = Date.now(), delta = now - (touch.last || now)
+ touch.el = $(parentIfText(e.touches[0].target))
+ touchTimeout && clearTimeout(touchTimeout)
+ touch.x1 = e.touches[0].pageX
+ touch.y1 = e.touches[0].pageY
+ if (delta > 0 && delta <= 250) touch.isDoubleTap = true
+ touch.last = now
+ setTimeout(longTap, longTapDelay)
}).bind('touchmove', function(e){
- touch.x2 = e.touches[0].pageX;
- touch.y2 = e.touches[0].pageY;
+ touch.x2 = e.touches[0].pageX
+ touch.y2 = e.touches[0].pageY
}).bind('touchend', function(e){
if (touch.isDoubleTap) {
- touch.el.trigger('doubleTap');
- touch = {};
+ touch.el.trigger('doubleTap')
+ touch = {}
} else if (touch.x2 > 0 || touch.y2 > 0) {
(Math.abs(touch.x1 - touch.x2) > 30 || Math.abs(touch.y1 - touch.y2) > 30) &&
touch.el.trigger('swipe') &&
- touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)));
- touch.x1 = touch.x2 = touch.y1 = touch.y2 = touch.last = 0;
+ touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
+ touch.x1 = touch.x2 = touch.y1 = touch.y2 = touch.last = 0
} else if ('last' in touch) {
- touch.el.trigger('tap');
+ touch.el.trigger('tap')
touchTimeout = setTimeout(function(){
- touchTimeout = null;
- touch.el.trigger('singleTap');
- touch = {};
- }, 250);
+ touchTimeout = null
+ touch.el.trigger('singleTap')
+ touch = {}
+ }, 250)
}
- }).bind('touchcancel', function(){ touch = {} });
- });
+ }).bind('touchcancel', function(){ touch = {} })
+ })
- ['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(m){
+ ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(m){
$.fn[m] = function(callback){ return this.bind(m, callback) }
- });
-})(Zepto);
+ })
+})(Zepto)

10 comments on commit 68cbe1f

@indutny

just... why?

@manuelkiessling

NOOOOOOOOOOOO!!!!!

@oslego

Zepto is experiencing a drastic diet! :)
@madrobby Could you please explain some of the reasoning for this?

@bartzon

;+1 on this commit

@LinusU

But, but, but... why? To decrease file size? That should be a job for the minifier!

@madrobby
Owner

Please see http://mislav.uniqpath.com/2010/05/semicolons/ for why we're doing this. It's purely a stylistic issue, with less typing for us and the core team prefers this style.

@cristibalan

What Thomas said.

Also, I really really hate all the uglifiers and minifiers. They make source viewing and poking very difficult and I hope the trend of taking out semicolons encourages people to leave their code readable to humans.

I learned a ton while I was starting out by viewing the source and looking at how things were made. Won't you please think of the children?

@mislav
Collaborator

Please refer to the following flowchart when making decisions about semicolons.

semicolons decision

@smolotov

Like it! :)
Why not get rid of the semicolon in ;(function($){...})(Zepto) by using !function($){...}(Zepto)?

@madrobby
Owner

@smolotov It's purely stylistic and we want simple rules, so it's easier to do the same before any statement that starts with ( or [. We leave more optimizations to UglifyJS.

Please sign in to comment.