Commit 610ab137 authored by scottjehl's avatar scottjehl

Merge branch 'master' of https://github.com/jquery/jquery

parents 18fa1fd9 a8fa5f2e
Copyright (c) 2010 John Resig, http://jquery.com/ Copyright (c) 2011 John Resig, http://jquery.com/
Permission is hereby granted, free of charge, to any person obtaining Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the a copy of this software and associated documentation files (the
......
...@@ -24,10 +24,9 @@ BASE_FILES = ${SRC_DIR}/core.js\ ...@@ -24,10 +24,9 @@ BASE_FILES = ${SRC_DIR}/core.js\
${SRC_DIR}/manipulation.js\ ${SRC_DIR}/manipulation.js\
${SRC_DIR}/css.js\ ${SRC_DIR}/css.js\
${SRC_DIR}/ajax.js\ ${SRC_DIR}/ajax.js\
${SRC_DIR}/xhr.js\ ${SRC_DIR}/ajax/jsonp.js\
${SRC_DIR}/transports/jsonp.js\ ${SRC_DIR}/ajax/script.js\
${SRC_DIR}/transports/script.js\ ${SRC_DIR}/ajax/xhr.js\
${SRC_DIR}/transports/xhr.js\
${SRC_DIR}/effects.js\ ${SRC_DIR}/effects.js\
${SRC_DIR}/offset.js\ ${SRC_DIR}/offset.js\
${SRC_DIR}/dimensions.js ${SRC_DIR}/dimensions.js
...@@ -79,13 +78,13 @@ init: ...@@ -79,13 +78,13 @@ init:
jquery: ${JQ} jquery: ${JQ}
jq: ${JQ} jq: ${JQ}
${JQ}: ${MODULES} ${DIST_DIR} ${JQ}: ${MODULES} | ${DIST_DIR}
@@echo "Building" ${JQ} @@echo "Building" ${JQ}
@@cat ${MODULES} | \ @@cat ${MODULES} | \
sed 's/.function..jQuery...{//' | \ sed 's/.function..jQuery...{//' | \
sed 's/}...jQuery..;//' | \ sed 's/}...jQuery..;//' | \
sed 's/Date:./&'"${DATE}"'/' | \ sed 's/@DATE/'"${DATE}"'/' | \
${VER} > ${JQ}; ${VER} > ${JQ};
${SRC_DIR}/selector.js: ${SIZZLE_DIR}/sizzle.js ${SRC_DIR}/selector.js: ${SIZZLE_DIR}/sizzle.js
......
...@@ -9,7 +9,27 @@ test_dir = File.join( prefix, 'test' ) ...@@ -9,7 +9,27 @@ test_dir = File.join( prefix, 'test' )
# setting DIST_DIR before calling rake # setting DIST_DIR before calling rake
dist_dir = ENV['DIST_DIR'] || File.join( prefix, 'dist' ) dist_dir = ENV['DIST_DIR'] || File.join( prefix, 'dist' )
base_files = %w{intro core support data queue attributes event selector traversing manipulation css ajax xhr transports/jsonp transports/script transports/xhr effects offset dimensions outro}.map { |js| File.join( src_dir, "#{js}.js" ) } base_files = %w{
intro
core
support
data
queue
attributes
event
selector
traversing
manipulation
css
ajax
ajax/jsonp
ajax/script
ajax/xhr
effects
offset
dimensions
outro
}.map { |js| File.join( src_dir, "#{js}.js" ) }
# Sizzle, QUnit and jQuery files/dirs # Sizzle, QUnit and jQuery files/dirs
sizzle_dir = File.join( src_dir, "sizzle" ) sizzle_dir = File.join( src_dir, "sizzle" )
...@@ -89,7 +109,11 @@ file jq => [dist_dir, base_files].flatten do ...@@ -89,7 +109,11 @@ file jq => [dist_dir, base_files].flatten do
puts "Building jquery.js..." puts "Building jquery.js..."
File.open(jq, 'w') do |f| File.open(jq, 'w') do |f|
f.write cat(base_files).gsub(/(Date:.)/, "\\1#{date}" ).gsub(/@VERSION/, version) f.write cat(base_files).
gsub(/@DATE/, date).
gsub(/@VERSION/, version).
gsub(/.function..jQuery...\{/, '').
gsub(/\}...jQuery..;/, '')
end end
end end
......
...@@ -63,10 +63,9 @@ ...@@ -63,10 +63,9 @@
<fileset file="src/manipulation.js" /> <fileset file="src/manipulation.js" />
<fileset file="src/css.js" /> <fileset file="src/css.js" />
<fileset file="src/ajax.js" /> <fileset file="src/ajax.js" />
<fileset file="src/xhr.js" /> <fileset file="src/ajax/jsonp.js" />
<fileset file="src/transports/jsonp.js" /> <fileset file="src/ajax/script.js" />
<fileset file="src/transports/script.js" /> <fileset file="src/ajax/xhr.js" />
<fileset file="src/transports/xhr.js" />
<fileset file="src/effects.js" /> <fileset file="src/effects.js" />
<fileset file="src/offset.js" /> <fileset file="src/offset.js" />
<fileset file="src/dimensions.js" /> <fileset file="src/dimensions.js" />
...@@ -77,7 +76,7 @@ ...@@ -77,7 +76,7 @@
<arg line="log -1 --pretty=format:%ad" /> <arg line="log -1 --pretty=format:%ad" />
</exec> </exec>
<replaceregexp match="(\(\s*function\s*\(\s*jQuery\s*\)\s*\{)|(\}\s*\)\s*\(\s*jQuery\s*\)\s*;)" flags="g" replace="" file="${JQ}" /> <replaceregexp match="(\(\s*function\s*\(\s*jQuery\s*\)\s*\{)|(\}\s*\)\s*\(\s*jQuery\s*\)\s*;)" flags="g" replace="" file="${JQ}" />
<replaceregexp match="Date: " replace="Date: ${date}" file="${JQ}" /> <replaceregexp match="@DATE" replace="${date}" file="${JQ}" />
<echo message="${JQ} built." /> <echo message="${JQ} built." />
</target> </target>
......
This diff is collapsed.
(function( jQuery ) {
var jsc = jQuery.now(),
jsre = /(\=)(?:\?|%3F)(&|$)|()(?:\?\?|%3F%3F)()/i,
rquery_jsonp = /\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return "jsonp" + jsc++;
}
// Normalize jsonp queries
// 1) put callback parameter in url or data
// 2) sneakily ensure transportDataType is always jsonp for jsonp requests
}).ajaxPrefilter("json jsonp", function(s, originalSettings) {
if ( s.dataTypes[ 0 ] === "jsonp" ||
originalSettings.jsonp ||
originalSettings.jsonpCallback ||
jsre.test(s.url) ||
typeof(s.data) === "string" && jsre.test(s.data) ) {
var jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
url = s.url.replace(jsre, "$1" + jsonpCallback + "$2"),
data = s.url === url && typeof(s.data) === "string" ? s.data.replace(jsre, "$1" + jsonpCallback + "$2") : s.data;
if ( url === s.url && data === s.data ) {
url += (rquery_jsonp.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
s.url = url;
s.data = data;
s.dataTypes[ 0 ] = "jsonp";
}
// Bind transport to jsonp dataType
}).ajaxTransport("jsonp", function(s) {
// Put callback in place
var responseContainer,
jsonpCallback = s.jsonpCallback,
previous = window[ jsonpCallback ];
window [ jsonpCallback ] = function( response ) {
responseContainer = [response];
};
s.complete = [function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( previous) {
if ( responseContainer && jQuery.isFunction ( previous ) ) {
window[ jsonpCallback ] ( responseContainer[0] );
}
} else {
// else, more memory leak avoidance
try{ delete window[ jsonpCallback ]; } catch(e){}
}
}, s.complete ];
// Sneakily ensure this will be handled as json
s.dataTypes[ 0 ] = "json";
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( ! responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// Delegate to script transport
return "script";
});
})( jQuery );
(function( jQuery ) { (function( jQuery ) {
// Install text to script executor // Install script dataType
jQuery.extend( true, jQuery.ajaxSettings , { jQuery.ajaxSetup({
accepts: { accepts: {
script: "text/javascript, application/javascript" script: "text/javascript, application/javascript"
}, },
autoDataType: { contents: {
script: /javascript/ script: /javascript/
}, },
dataConverters: { converters: {
"text => script": jQuery.globalEval "text script": jQuery.globalEval
} }
} );
// Bind script tag hack transport // Bind script tag hack transport
jQuery.xhr.bindTransport("script", function(s) { }).ajaxTransport("script", function(s) {
// Handle cache special case // Handle cache special case
if ( s.cache === undefined ) { if ( s.cache === undefined ) {
...@@ -47,10 +46,9 @@ jQuery.xhr.bindTransport("script", function(s) { ...@@ -47,10 +46,9 @@ jQuery.xhr.bindTransport("script", function(s) {
script.src = s.url; script.src = s.url;
// Attach handlers for all browsers // Attach handlers for all browsers
script.onload = script.onreadystatechange = function(statusText) { script.onload = script.onreadystatechange = function( _ , isAbort ) {
if ( (!script.readyState || if ( ! script.readyState || /loaded|complete/.test( script.readyState ) ) {
script.readyState === "loaded" || script.readyState === "complete") ) {
// Handle memory leak in IE // Handle memory leak in IE
script.onload = script.onreadystatechange = null; script.onload = script.onreadystatechange = null;
...@@ -60,10 +58,13 @@ jQuery.xhr.bindTransport("script", function(s) { ...@@ -60,10 +58,13 @@ jQuery.xhr.bindTransport("script", function(s) {
head.removeChild( script ); head.removeChild( script );
} }
script = undefined; // Dereference the script
script = 0;
// Callback & dereference // Callback if not abort
callback(statusText ? 0 : 200, statusText || "success"); if ( ! isAbort ) {
callback( 200, "success" );
}
} }
}; };
// Use insertBefore instead of appendChild to circumvent an IE6 bug. // Use insertBefore instead of appendChild to circumvent an IE6 bug.
...@@ -71,9 +72,9 @@ jQuery.xhr.bindTransport("script", function(s) { ...@@ -71,9 +72,9 @@ jQuery.xhr.bindTransport("script", function(s) {
head.insertBefore( script, head.firstChild ); head.insertBefore( script, head.firstChild );
}, },
abort: function(statusText) { abort: function() {
if ( script ) { if ( script ) {
script.onload(statusText); script.onload(0,1);
} }
} }
}; };
......
(function( jQuery ) { (function( jQuery ) {
var // Next fake timer id var // Next active xhr id
xhrPollingId = jQuery.now(), xhrId = jQuery.now(),
// Callbacks hashtable // active xhrs
xhrs = {}, xhrs = {},
// #5280: see end of file // #5280: see below
xhrUnloadAbortMarker = []; xhrUnloadAbortInstalled;
jQuery.xhr.bindTransport( function( s , determineDataType ) { jQuery.ajaxTransport( function( s , determineDataType ) {
// Cross domain only allowed if supported through XMLHttpRequest // Cross domain only allowed if supported through XMLHttpRequest
if ( ! s.crossDomain || jQuery.support.cors ) { if ( ! s.crossDomain || jQuery.support.cors ) {
...@@ -21,6 +21,24 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) { ...@@ -21,6 +21,24 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) {
send: function(headers, complete) { send: function(headers, complete) {
// #5280: we need to abort on unload or IE will keep connections alive
if ( ! xhrUnloadAbortInstalled ) {
xhrUnloadAbortInstalled = 1;
jQuery(window).bind( "unload" , function() {
// Abort all pending requests
jQuery.each(xhrs, function(_, xhr) {
if ( xhr.onreadystatechange ) {
xhr.onreadystatechange( 1 );
}
});
});
}
// Get a new xhr
var xhr = s.xhr(), var xhr = s.xhr(),
handle; handle;
...@@ -35,7 +53,7 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) { ...@@ -35,7 +53,7 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) {
// Requested-With header // Requested-With header
// Not set for crossDomain requests with no content // Not set for crossDomain requests with no content
// (see why at http://trac.dojotoolkit.org/ticket/9486) // (see why at http://trac.dojotoolkit.org/ticket/9486)
// Won't change header if already provided in beforeSend // Won't change header if already provided
if ( ! ( s.crossDomain && ! s.hasContent ) && ! headers["x-requested-with"] ) { if ( ! ( s.crossDomain && ! s.hasContent ) && ! headers["x-requested-with"] ) {
headers["x-requested-with"] = "XMLHttpRequest"; headers["x-requested-with"] = "XMLHttpRequest";
} }
...@@ -58,40 +76,35 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) { ...@@ -58,40 +76,35 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) {
} }
// Listener // Listener
callback = function ( abortStatusText ) { callback = function( _ , isAbort ) {
// Was never called and is aborted or complete // Was never called and is aborted or complete
if ( callback && ( abortStatusText || xhr.readyState === 4 ) ) { if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = 0;
// Do not listen anymore // Do not keep as active anymore
// and store back into pool
if (handle) { if (handle) {
xhr.onreadystatechange = jQuery.noop; xhr.onreadystatechange = jQuery.noop;
delete xhrs[ handle ]; delete xhrs[ handle ];
handle = undefined;
} }
callback = 0; // If it's an abort
if ( isAbort ) {
// Get info
var status, statusText, response, responseHeaders;
if ( abortStatusText ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) { if ( xhr.readyState !== 4 ) {
xhr.abort(); xhr.abort();
} }
// Stop here if unloadAbort
if ( abortStatusText === xhrUnloadAbortMarker ) {
return;
}
status = 0;
statusText = abortStatusText;
} else { } else {
status = xhr.status; // Get info
var status = xhr.status,
statusText,
response,
responseHeaders = xhr.getAllResponseHeaders();
try { // Firefox throws an exception when accessing statusText for faulty cross-domain requests try { // Firefox throws an exception when accessing statusText for faulty cross-domain requests
...@@ -103,8 +116,6 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) { ...@@ -103,8 +116,6 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) {
} }
responseHeaders = xhr.getAllResponseHeaders();
// Filter status for non standard behaviours // Filter status for non standard behaviours
// (so many they seem to be the actual "standard") // (so many they seem to be the actual "standard")
status = status =
...@@ -130,20 +141,18 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) { ...@@ -130,20 +141,18 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) {
status status
); );
// Guess response if needed & update datatype accordingly // Guess response & update dataType accordingly
if ( status >= 200 && status < 300 ) {
response = response =
determineDataType( determineDataType(
s, s,
xhr.getResponseHeader("content-type"), xhr.getResponseHeader("content-type"),
xhr.responseText, xhr.responseText,
xhr.responseXML ); xhr.responseXML );
}
}
// Call complete // Call complete
complete(status,statusText,response,responseHeaders); complete(status,statusText,response,responseHeaders);
} }
}
}; };
// if we're in sync mode // if we're in sync mode
...@@ -155,37 +164,20 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) { ...@@ -155,37 +164,20 @@ jQuery.xhr.bindTransport( function( s , determineDataType ) {
} else { } else {
// Listener is externalized to handle abort on unload // Add to list of active xhrs
handle = xhrPollingId++; handle = xhrId++;
xhrs[ handle ] = xhr; xhrs[ handle ] = xhr;
xhr.onreadystatechange = function() { xhr.onreadystatechange = callback;
callback();
};
} }
}, },
abort: function(statusText) { abort: function() {
if ( callback ) { if ( callback ) {
callback(statusText); callback(0,1);
} }
} }
}; };
} }
}); });
// #5280: we need to abort on unload or IE will keep connections alive
jQuery(window).bind( "unload" , function() {
// Abort all pending requests
jQuery.each(xhrs, function(_, xhr) {
if ( xhr.onreadystatechange ) {
xhr.onreadystatechange( xhrUnloadAbortMarker );
}
});
// Resest polling structure to be safe
xhrs = {};
});
})( jQuery ); })( jQuery );
...@@ -60,8 +60,8 @@ var jQuery = function( selector, context ) { ...@@ -60,8 +60,8 @@ var jQuery = function( selector, context ) {
// Has the ready events already been bound? // Has the ready events already been bound?
readyBound = false, readyBound = false,
// The functions to execute on DOM ready // The deferred used on DOM ready
readyList = [], readyList,
// The ready event handler // The ready event handler
DOMContentLoaded, DOMContentLoaded,
...@@ -129,7 +129,7 @@ jQuery.fn = jQuery.prototype = { ...@@ -129,7 +129,7 @@ jQuery.fn = jQuery.prototype = {
} else { } else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; selector = (ret.cacheable ? jQuery(ret.fragment).clone()[0] : ret.fragment).childNodes;
} }
return jQuery.merge( this, selector ); return jQuery.merge( this, selector );
...@@ -253,22 +253,12 @@ jQuery.fn = jQuery.prototype = { ...@@ -253,22 +253,12 @@ jQuery.fn = jQuery.prototype = {
return jQuery.each( this, callback, args ); return jQuery.each( this, callback, args );
}, },
ready: function( fn ) { ready: function() {
// Attach the listeners // Attach the listeners
jQuery.bindReady(); jQuery.bindReady();
// If the DOM is already ready // Change ready & apply
if ( jQuery.isReady ) { return ( jQuery.fn.ready = readyList.done ).apply( this , arguments );
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
} else if ( readyList ) {
// Add the function to the wait list
readyList.push( fn );
}
return this;
}, },
eq: function( i ) { eq: function( i ) {
...@@ -415,25 +405,13 @@ jQuery.extend({ ...@@ -415,25 +405,13 @@ jQuery.extend({
} }
// If there are functions bound, to execute // If there are functions bound, to execute
if ( readyList ) { readyList.fire( document , [ jQuery ] );
// Execute all of them
var fn,
i = 0,
ready = readyList;
// Reset the list of functions
readyList = null;
while ( (fn = ready[ i++ ]) ) {
fn.call( document, jQuery );
}
// Trigger any bound ready events // Trigger any bound ready events
if ( jQuery.fn.trigger ) { if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" ); jQuery( document ).trigger( "ready" ).unbind( "ready" );
} }
} }
}
}, },
bindReady: function() { bindReady: function() {
...@@ -566,6 +544,28 @@ jQuery.extend({ ...@@ -566,6 +544,28 @@ jQuery.extend({
} }
}, },
// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {}, noop: function() {},
// Evalulates a script in a global context // Evalulates a script in a global context
...@@ -801,6 +801,151 @@ jQuery.extend({ ...@@ -801,6 +801,151 @@ jQuery.extend({
return (new Date()).getTime(); return (new Date()).getTime();
}, },
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function () {
if ( ! cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length ; i < length ; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred , elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.fire( _fired[ 0 ] , _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
fire: function( context , args ) {
if ( ! cancelled && ! fired && ! firing ) {
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context , args );
}
}
finally {
fired = [ context , args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.fire( jQuery.isFunction( this.promise ) ? this.promise() : this , arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
// Typical success/error system
Deferred: function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred();
// Add errorDeferred methods and redefine cancel
jQuery.extend( deferred , {
then: function( doneCallbacks , failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
fail: failDeferred.done,
fireReject: failDeferred.fire,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
obj = obj || {};
jQuery.each( "then done fail isResolved isRejected".split( " " ) , function( _ , method ) {
obj[ method ] = deferred[ method ];
});
obj.promise = function() {
return obj;
};
return obj;
}
} );
// Make sure only one callback list will be used
deferred.then( failDeferred.cancel , deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred , deferred );
}
return deferred;
},
// Deferred helper
when: function( object ) {
object = object && jQuery.isFunction( object.promise ) ?
object :
jQuery.Deferred().resolve( object );
return object.promise();
},
// Use of jQuery.browser is frowned upon. // Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser // More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) { uaMatch: function( ua ) {
...@@ -818,6 +963,9 @@ jQuery.extend({ ...@@ -818,6 +963,9 @@ jQuery.extend({
browser: {} browser: {}
}); });
// Create readyList deferred
readyList = jQuery._Deferred();
// Populate the class2type map // Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase(); class2type[ "[object " + name + "]" ] = name.toLowerCase();
......
...@@ -12,9 +12,6 @@ var ralpha = /alpha\([^)]*\)/i, ...@@ -12,9 +12,6 @@ var ralpha = /alpha\([^)]*\)/i,
cssHeight = [ "Top", "Bottom" ], cssHeight = [ "Top", "Bottom" ],
curCSS, curCSS,
getComputedStyle,
currentStyle,
fcamelCase = function( all, letter ) { fcamelCase = function( all, letter ) {
return letter.toUpperCase(); return letter.toUpperCase();
}; };
...@@ -172,10 +169,6 @@ jQuery.each(["height", "width"], function( i, name ) { ...@@ -172,10 +169,6 @@ jQuery.each(["height", "width"], function( i, name ) {
if ( val <= 0 ) { if ( val <= 0 ) {
val = curCSS( elem, name, name ); val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) { if ( val != null ) {
// Should return "auto" instead of 0, use 0 for // Should return "auto" instead of 0, use 0 for
// temporary backwards-compat // temporary backwards-compat
...@@ -241,7 +234,7 @@ if ( !jQuery.support.opacity ) { ...@@ -241,7 +234,7 @@ if ( !jQuery.support.opacity ) {
} }
if ( document.defaultView && document.defaultView.getComputedStyle ) { if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, newName, name ) { curCSS = function( elem, newName, name ) {
var ret, defaultView, computedStyle; var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase(); name = name.replace( rupper, "-$1" ).toLowerCase();
...@@ -259,10 +252,8 @@ if ( document.defaultView && document.defaultView.getComputedStyle ) { ...@@ -259,10 +252,8 @@ if ( document.defaultView && document.defaultView.getComputedStyle ) {
return ret; return ret;
}; };
} } else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ], ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style; style = elem.style;
...@@ -291,8 +282,6 @@ if ( document.documentElement.currentStyle ) { ...@@ -291,8 +282,6 @@ if ( document.documentElement.currentStyle ) {
}; };
} }
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) { function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight, var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight; val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
......
...@@ -10,7 +10,8 @@ jQuery.extend({ ...@@ -10,7 +10,8 @@ jQuery.extend({
uuid: 0, uuid: 0,
// Unique for each copy of jQuery on the page // Unique for each copy of jQuery on the page
expando: "jQuery" + jQuery.now(), // Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you // The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them. // attempt to add expando properties to them.
...@@ -21,6 +22,14 @@ jQuery.extend({ ...@@ -21,6 +22,14 @@ jQuery.extend({
"applet": true "applet": true
}, },
hasData: function( elem ) {
if ( elem.nodeType ) {
elem = jQuery.cache[ elem[jQuery.expando] ];
}
return !!elem && !jQuery.isEmptyObject(elem);
},
data: function( elem, name, data ) { data: function( elem, name, data ) {
if ( !jQuery.acceptData( elem ) ) { if ( !jQuery.acceptData( elem ) ) {
return; return;
......
...@@ -337,7 +337,7 @@ jQuery.fx.prototype = { ...@@ -337,7 +337,7 @@ jQuery.fx.prototype = {
} }
var r = parseFloat( jQuery.css( this.elem, this.prop ) ); var r = parseFloat( jQuery.css( this.elem, this.prop ) );
return r && r > -10000 ? r : 0; return r || 0;
}, },
// Start an animation from one number to another // Start an animation from one number to another
......
...@@ -600,6 +600,12 @@ jQuery.Event = function( src ) { ...@@ -600,6 +600,12 @@ jQuery.Event = function( src ) {
if ( src && src.type ) { if ( src && src.type ) {
this.originalEvent = src; this.originalEvent = src;
this.type = src.type; this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
// Event type // Event type
} else { } else {
this.type = src; this.type = src;
...@@ -1177,21 +1183,4 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl ...@@ -1177,21 +1183,4 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl
} }
}); });
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
jQuery(window).bind("unload", function() {
for ( var id in jQuery.cache ) {
if ( jQuery.cache[ id ].handle ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
} catch(e) {}
}
}
});
}
})( jQuery ); })( jQuery );
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
* Copyright 2010, The Dojo Foundation * Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses. * Released under the MIT, BSD, and GPL Licenses.
* *
* Date: * Date: @DATE
*/ */
(function( window, undefined ) { (function( window, undefined ) {
......
...@@ -370,14 +370,18 @@ function root( elem, cur ) { ...@@ -370,14 +370,18 @@ function root( elem, cur ) {
} }
function cloneCopyEvent(orig, ret) { function cloneCopyEvent(orig, ret) {
var i = 0; ret.each(function (nodeIndex) {
if ( this.nodeType !== 1 || !jQuery.hasData(orig[nodeIndex]) ) {
ret.each(function() {
if ( this.nodeType !== 1 || this.nodeName !== (orig[i] && orig[i].nodeName) ) {
return; return;
} }
var oldData = jQuery.data( orig[i++] ), // XXX remove for 1.5 RC or merge back in if there is actually a reason for this check that has been
// unexposed by unit tests
if ( this.nodeName !== (orig[nodeIndex] && orig[nodeIndex].nodeName) ) {
throw "Cloned data mismatch";
}
var oldData = jQuery.data( orig[nodeIndex] ),
curData = jQuery.data( this, oldData ), curData = jQuery.data( this, oldData ),
events = oldData && oldData.events; events = oldData && oldData.events;
...@@ -386,8 +390,8 @@ function cloneCopyEvent(orig, ret) { ...@@ -386,8 +390,8 @@ function cloneCopyEvent(orig, ret) {
curData.events = {}; curData.events = {};
for ( var type in events ) { for ( var type in events ) {
for ( var handler in events[ type ] ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); jQuery.event.add( this, type, events[ type ][ i ], events[ type ][ i ].data );
} }
} }
} }
...@@ -416,15 +420,29 @@ function cloneFixAttributes(src, dest) { ...@@ -416,15 +420,29 @@ function cloneFixAttributes(src, dest) {
if ( nodeName === "object" ) { if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML; dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox // IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button // or radio button. Worse, IE6-7 fail to give the cloned element
} else if ( nodeName === "input" && src.checked ) { // a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked; dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected // IE6-8 fails to return the selected option to the default selected
// state when cloning options // state when cloning options
} else if ( nodeName === "option" ) { } else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected; dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
} }
// Event data gets referenced instead of copied if the expando // Event data gets referenced instead of copied if the expando
...@@ -436,12 +454,12 @@ jQuery.buildFragment = function( args, nodes, scripts ) { ...@@ -436,12 +454,12 @@ jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) strings that are associated with the main document // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them // Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
!rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true; cacheable = true;
cacheresults = jQuery.fragments[ args[0] ]; cacheresults = jQuery.fragments[ args[0] ];
...@@ -613,6 +631,11 @@ jQuery.extend({ ...@@ -613,6 +631,11 @@ jQuery.extend({
jQuery.removeEvent( elem, type, data.handle ); jQuery.removeEvent( elem, type, data.handle );
} }
} }
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
} }
if ( deleteExpando ) { if ( deleteExpando ) {
......
...@@ -147,7 +147,7 @@ ...@@ -147,7 +147,7 @@
jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
} }
div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>"; div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
var tds = div.getElementsByTagName("td"); var tds = div.getElementsByTagName("td");
// Check if table cells still have offsetWidth/Height when they are set // Check if table cells still have offsetWidth/Height when they are set
......
(function( jQuery ) {
var jsc = jQuery.now(),
jsre = /\=\?(&|$)/,
rquery_jsonp = /\?/;
// Default jsonp callback name
jQuery.ajaxSettings.jsonpCallback = function() {
return "jsonp" + jsc++;
};
// Normalize jsonp queries
// 1) put callback parameter in url or data
// 2) ensure transportDataType is json
// 3) ensure options jsonp is always provided so that jsonp requests are always
// json request with the jsonp option set
jQuery.xhr.prefilter( function(s) {
var transportDataType = s.dataTypes[0];
if ( s.jsonp ||
transportDataType === "jsonp" ||
transportDataType === "json" && ( jsre.test(s.url) || typeof(s.data) === "string" && jsre.test(s.data) ) ) {
var jsonp = s.jsonp = s.jsonp || "callback",
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
url = s.url.replace(jsre, "=" + jsonpCallback + "$1"),
data = s.url == url && typeof(s.data) === "string" ? s.data.replace(jsre, "=" + jsonpCallback + "$1") : s.data;
if ( url == s.url && data == s.data ) {
url = url += (rquery_jsonp.test( url ) ? "&" : "?") + jsonp + "=" + jsonpCallback;
}
s.url = url;
s.data = data;
s.dataTypes[0] = "json";
}
});
// Bind transport to json dataType
jQuery.xhr.bindTransport("json", function(s) {
if ( s.jsonp ) {
// Put callback in place
var responseContainer,
jsonpCallback = s.jsonpCallback,
previous = window[ jsonpCallback ];
window [ jsonpCallback ] = function( response ) {
responseContainer = [response];
};
s.complete = [function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( previous) {
if ( responseContainer && jQuery.isFunction ( previous ) ) {
window[ jsonpCallback ] ( responseContainer[0] );
}
} else {
// else, more memory leak avoidance
try{ delete window[ jsonpCallback ]; } catch(e){}
}
}, s.complete ];
// Use data converter to retrieve json after script execution
s.dataConverters["script => json"] = function() {
if ( ! responseContainer ) {
jQuery.error("Callback '" + jsonpCallback + "' was not called");
}
return responseContainer[ 0 ];
};
// Delegate to script transport
return "script";
}
});
})( jQuery );
This diff is collapsed.
<?php
header("HTTP/1.0 400 Bad Request");
echo "plain text message";
\ No newline at end of file
...@@ -6,15 +6,11 @@ $headers = array(); ...@@ -6,15 +6,11 @@ $headers = array();
foreach( $_SERVER as $key => $value ) { foreach( $_SERVER as $key => $value ) {
if ( substr( $key , 0 , 5 ) == "HTTP_" ) { $key = str_replace( "_" , "-" , substr( $key , 0 , 5 ) == "HTTP_" ? substr( $key , 5 ) : $key );
$key = str_replace( "_" , "-" , substr( $key , 5) );
$headers[ $key ] = $value; $headers[ $key ] = $value;
}
} }
foreach( explode( "_" , $_GET[ "keys" ] ) as $key ) { foreach( explode( "_" , $_GET[ "keys" ] ) as $key ) {
echo "$key: " . $headers[ strtoupper( $key ) ] . "\n"; echo "$key: " . @$headers[ strtoupper( $key ) ] . "\n";
} }
<?php <?php
error_reporting(0); error_reporting(0);
$callback = $_REQUEST['callback']; $callback = $_REQUEST['callback'];
if ( ! $callback ) {
$callback = explode("?",end(explode("/",$_SERVER['REQUEST_URI'])));
$callback = $callback[0];
}
$json = $_REQUEST['json']; $json = $_REQUEST['json'];
if($json) { if($json) {
echo $callback . '([ {"name": "John", "age": 21}, {"name": "Peter", "age": 25 } ])'; echo $callback . '([ {"name": "John", "age": 21}, {"name": "Peter", "age": 25 } ])';
......
...@@ -20,10 +20,9 @@ ...@@ -20,10 +20,9 @@
<script src="../src/manipulation.js"></script> <script src="../src/manipulation.js"></script>
<script src="../src/css.js"></script> <script src="../src/css.js"></script>
<script src="../src/ajax.js"></script> <script src="../src/ajax.js"></script>
<script src="../src/xhr.js"></script> <script src="../src/ajax/jsonp.js"></script>
<script src="../src/transports/jsonp.js"></script> <script src="../src/ajax/script.js"></script>
<script src="../src/transports/script.js"></script> <script src="../src/ajax/xhr.js"></script>
<script src="../src/transports/xhr.js"></script>
<script src="../src/effects.js"></script> <script src="../src/effects.js"></script>
<script src="../src/offset.js"></script> <script src="../src/offset.js"></script>
<script src="../src/dimensions.js"></script> <script src="../src/dimensions.js"></script>
......
This diff is collapsed.
...@@ -12,7 +12,7 @@ test("Basic requirements", function() { ...@@ -12,7 +12,7 @@ test("Basic requirements", function() {
}); });
test("jQuery()", function() { test("jQuery()", function() {
expect(23); expect(24);
// Basic constructor's behavior // Basic constructor's behavior
...@@ -84,6 +84,11 @@ test("jQuery()", function() { ...@@ -84,6 +84,11 @@ test("jQuery()", function() {
exec = true; exec = true;
elem.click(); elem.click();
for ( var i = 0; i < 3; ++i ) {
elem = jQuery("<input type='text' value='TEST' />");
}
equals( elem[0].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug #6655)" );
}); });
test("selector state", function() { test("selector state", function() {
...@@ -902,3 +907,159 @@ test("jQuery.parseJSON", function(){ ...@@ -902,3 +907,159 @@ test("jQuery.parseJSON", function(){
ok( true, "Test malformed JSON string." ); ok( true, "Test malformed JSON string." );
} }
}); });
test("jQuery._Deferred()", function() {
expect( 10 );
var deferred,
object,
test;
deferred = jQuery._Deferred();
test = false;
deferred.done( function( value ) {
equals( value , "value" , "Test pre-resolve callback" );
test = true;
} );
deferred.resolve( "value" );
ok( test , "Test pre-resolve callbacks called right away" );
test = false;
deferred.done( function( value ) {
equals( value , "value" , "Test post-resolve callback" );
test = true;
} );
ok( test , "Test post-resolve callbacks called right away" );
deferred.cancel();
test = true;
deferred.done( function() {
ok( false , "Cancel was ignored" );
test = false;
} );
ok( test , "Test cancel" );
deferred = jQuery._Deferred().resolve();
try {
deferred.done( function() {
throw "Error";
} , function() {
ok( true , "Test deferred do not cancel on exception" );
} );
} catch( e ) {
strictEqual( e , "Error" , "Test deferred propagates exceptions");
deferred.done();
}
test = "";
deferred = jQuery._Deferred().done( function() {
test += "A";
}, function() {
test += "B";
} ).resolve();
strictEqual( test , "AB" , "Test multiple done parameters" );
test = "";
deferred.done( function() {
deferred.done( function() {
test += "C";
} );
test += "A";
}, function() {
test += "B";
} );
strictEqual( test , "ABC" , "Test done callbacks order" );
deferred = jQuery._Deferred();
deferred.fire( jQuery , [ document ] ).done( function( doc ) {
ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" );
});
});
test("jQuery.Deferred()", function() {
expect( 4 );
jQuery.Deferred( function( defer ) {
strictEqual( this , defer , "Defer passed as this & first argument" );
this.resolve( "done" );
}).then( function( value ) {
strictEqual( value , "done" , "Passed function executed" );
});
jQuery.Deferred().resolve().then( function() {
ok( true , "Success on resolve" );
}, function() {
ok( false , "Error on resolve" );
});
jQuery.Deferred().reject().then( function() {
ok( false , "Success on reject" );
}, function() {
ok( true , "Error on reject" );
});
});
test("jQuery.when()", function() {
expect( 21 );
// Some other objects
jQuery.each( {
"an empty string": "",
"a non-empty string": "some string",
"zero": 0,
"a number other than zero": 1,
"true": true,
"false": false,
"null": null,
"undefined": undefined,
"a plain object": {}
} , function( message , value ) {
ok( jQuery.isFunction( jQuery.when( value ).then( function( resolveValue ) {
strictEqual( resolveValue , value , "Test the promise was resolved with " + message );
} ).promise ) , "Test " + message + " triggers the creation of a new Promise" );
} );
var cache, i;
for( i = 1 ; i < 4 ; i++ ) {
jQuery.when( cache || jQuery.Deferred( function() {
this.resolve( i );
}) ).then( function( value ) {
strictEqual( value , 1 , "Function executed" + ( i > 1 ? " only once" : "" ) );
cache = value;
}, function() {
ok( false , "Fail called" );
});
}
});
...@@ -78,6 +78,21 @@ test("jQuery.data", function() { ...@@ -78,6 +78,21 @@ test("jQuery.data", function() {
ok( jQuery.data( window, "BAD" ), "Make sure that the value was set." ); ok( jQuery.data( window, "BAD" ), "Make sure that the value was set." );
}); });
test("jQuery.hasData", function() {
expect(6);
function testData(obj) {
equals( jQuery.hasData(obj), false, "No data exists" );
jQuery.data( obj, "foo", "bar" );
equals( jQuery.hasData(obj), true, "Data exists" );
jQuery.removeData( obj, "foo" );
equals( jQuery.hasData(obj), false, "Data was removed" );
}
testData(document.createElement('div'));
testData({});
});
test(".data()", function() { test(".data()", function() {
expect(5); expect(5);
......
...@@ -560,6 +560,23 @@ jQuery.checkOverflowDisplay = function(){ ...@@ -560,6 +560,23 @@ jQuery.checkOverflowDisplay = function(){
start(); start();
} }
test("support negative values < -10000 (bug #7193)", function () {
expect(1);
stop();
jQuery.extend(jQuery.fx.step, {
"marginBottom": function(fx) {
equals( fx.cur(), -11000, "Element has margin-bottom of -11000" );
delete jQuery.fx.step.marginBottom;
}
});
jQuery("#main").css("marginBottom", "-11000px").animate({ marginBottom: "-11001px" }, {
duration: 1,
complete: start
});
});
test("JS Overflow and Display", function() { test("JS Overflow and Display", function() {
expect(2); expect(2);
stop(); stop();
......
...@@ -295,6 +295,41 @@ test("live/delegate immediate propagation", function() { ...@@ -295,6 +295,41 @@ test("live/delegate immediate propagation", function() {
$p.undelegate( "click" ); $p.undelegate( "click" );
}); });
test("bind/delegate bubbling, isDefaultPrevented (Bug #7793)", function() {
expect(2);
var $anchor2 = jQuery( "#anchor2" ),
$main = jQuery( "#main" ),
fakeClick = function($jq) {
// Use a native click so we don't get jQuery simulated bubbling
if ( document.createEvent ) {
var e = document.createEvent( "MouseEvents" );
e.initEvent( "click", true, true );
$jq[0].dispatchEvent(e);
}
else if ( $jq[0].click ) {
$jq[0].click(); // IE
}
};
$anchor2.click(function(e) {
e.preventDefault();
});
$main.delegate("#foo", "click", function(e) {
equals( e.isDefaultPrevented(), true, "isDefaultPrevented true passed to bubbled event" );
});
fakeClick( $anchor2 );
$anchor2.unbind( "click" );
$main.undelegate( "click" );
$anchor2.click(function(e) {
// Let the default action occur
});
$main.delegate("#foo", "click", function(e) {
equals( e.isDefaultPrevented(), false, "isDefaultPrevented false passed to bubbled event" );
});
fakeClick( $anchor2 );
$anchor2.unbind( "click" );
$main.undelegate( "click" );
});
test("bind(), iframes", function() { test("bind(), iframes", function() {
// events don't work with iframes, see #939 - this test fails in IE because of contentDocument // events don't work with iframes, see #939 - this test fails in IE because of contentDocument
var doc = jQuery("#loadediframe").contents(); var doc = jQuery("#loadediframe").contents();
......
module("manipulation"); module("manipulation");
// Ensure that an extended Array prototype doesn't break jQuery
Array.prototype.arrayProtoFn = function(arg) { throw("arrayProtoFn should not be called"); };
var bareObj = function(value) { return value; }; var bareObj = function(value) { return value; };
var functionReturningObj = function(value) { return (function() { return value; }); }; var functionReturningObj = function(value) { return (function() { return value; }); };
...@@ -51,7 +54,7 @@ test("text(Function) with incoming value", function() { ...@@ -51,7 +54,7 @@ test("text(Function) with incoming value", function() {
}); });
var testWrap = function(val) { var testWrap = function(val) {
expect(18); expect(19);
var defaultText = 'Try them out:' var defaultText = 'Try them out:'
var result = jQuery('#first').wrap(val( '<div class="red"><span></span></div>' )).text(); var result = jQuery('#first').wrap(val( '<div class="red"><span></span></div>' )).text();
equals( defaultText, result, 'Check for wrapping of on-the-fly html' ); equals( defaultText, result, 'Check for wrapping of on-the-fly html' );
...@@ -80,10 +83,20 @@ var testWrap = function(val) { ...@@ -80,10 +83,20 @@ var testWrap = function(val) {
equals( jQuery("#nonnodes > i").text(), j.text(), "Check node,textnode,comment wraps doesn't hurt text" ); equals( jQuery("#nonnodes > i").text(), j.text(), "Check node,textnode,comment wraps doesn't hurt text" );
// Try wrapping a disconnected node // Try wrapping a disconnected node
var cacheLength = 0;
for (var i in jQuery.cache) {
cacheLength++;
}
j = jQuery("<label/>").wrap(val( "<li/>" )); j = jQuery("<label/>").wrap(val( "<li/>" ));
equals( j[0].nodeName.toUpperCase(), "LABEL", "Element is a label" ); equals( j[0].nodeName.toUpperCase(), "LABEL", "Element is a label" );
equals( j[0].parentNode.nodeName.toUpperCase(), "LI", "Element has been wrapped" ); equals( j[0].parentNode.nodeName.toUpperCase(), "LI", "Element has been wrapped" );
for (i in jQuery.cache) {
cacheLength--;
}
equals(cacheLength, 0, "No memory leak in jQuery.cache (bug #7165)");
// Wrap an element containing a text node // Wrap an element containing a text node
j = jQuery("<span/>").wrap("<div>test</div>"); j = jQuery("<span/>").wrap("<div>test</div>");
equals( j[0].previousSibling.nodeType, 3, "Make sure the previous node is a text element" ); equals( j[0].previousSibling.nodeType, 3, "Make sure the previous node is a text element" );
...@@ -382,7 +395,7 @@ test("append(Function) with incoming value", function() { ...@@ -382,7 +395,7 @@ test("append(Function) with incoming value", function() {
}); });
test("append the same fragment with events (Bug #6997, 5566)", function () { test("append the same fragment with events (Bug #6997, 5566)", function () {
expect(4 + (document.fireEvent ? 1 : 0)); expect(2 + (document.fireEvent ? 1 : 0));
stop(1000); stop(1000);
var element; var element;
...@@ -413,14 +426,6 @@ test("append the same fragment with events (Bug #6997, 5566)", function () { ...@@ -413,14 +426,6 @@ test("append the same fragment with events (Bug #6997, 5566)", function () {
jQuery("#listWithTabIndex li").before(element); jQuery("#listWithTabIndex li").before(element);
jQuery("#listWithTabIndex li.test6997").eq(1).click(); jQuery("#listWithTabIndex li.test6997").eq(1).click();
element = jQuery("<select><option>Foo</option><option selected>Bar</option></select>");
equals( element.clone().find("option:selected").val(), element.find("option:selected").val(), "Selected option cloned correctly" );
element = jQuery("<input type='checkbox'>").attr('checked', 'checked');
equals( element.clone().is(":checked"), element.is(":checked"), "Checked input cloned correctly" );
}); });
test("appendTo(String|Element|Array&lt;Element&gt;|jQuery)", function() { test("appendTo(String|Element|Array&lt;Element&gt;|jQuery)", function() {
...@@ -856,7 +861,7 @@ test("replaceAll(String|Element|Array&lt;Element&gt;|jQuery)", function() { ...@@ -856,7 +861,7 @@ test("replaceAll(String|Element|Array&lt;Element&gt;|jQuery)", function() {
}); });
test("clone()", function() { test("clone()", function() {
expect(36); expect(37);
equals( 'This is a normal link: Yahoo', jQuery('#en').text(), 'Assert text for #en' ); equals( 'This is a normal link: Yahoo', jQuery('#en').text(), 'Assert text for #en' );
var clone = jQuery('#yahoo').clone(); var clone = jQuery('#yahoo').clone();
equals( 'Try them out:Yahoo', jQuery('#first').append(clone).text(), 'Check for clone' ); equals( 'Try them out:Yahoo', jQuery('#first').append(clone).text(), 'Check for clone' );
...@@ -914,10 +919,12 @@ test("clone()", function() { ...@@ -914,10 +919,12 @@ test("clone()", function() {
equals( clone.html(), div.html(), "Element contents cloned" ); equals( clone.html(), div.html(), "Element contents cloned" );
equals( clone[0].nodeName.toUpperCase(), "DIV", "DIV element cloned" ); equals( clone[0].nodeName.toUpperCase(), "DIV", "DIV element cloned" );
div = jQuery("<div/>").data({ a: true, b: true }); div = jQuery("<div/>").data({ a: true });
div = div.clone(true); var div2 = div.clone(true);
equals( div.data("a"), true, "Data cloned." ); equals( div2.data("a"), true, "Data cloned." );
equals( div.data("b"), true, "Data cloned." ); div2.data("a", false);
equals( div2.data("a"), false, "Ensure cloned element data object was correctly modified" );
equals( div.data("a"), true, "Ensure cloned element data object is copied, not referenced" );
var form = document.createElement("form"); var form = document.createElement("form");
form.action = "/test/"; form.action = "/test/";
...@@ -930,6 +937,28 @@ test("clone()", function() { ...@@ -930,6 +937,28 @@ test("clone()", function() {
equal( jQuery("body").clone().children()[0].id, "qunit-header", "Make sure cloning body works" ); equal( jQuery("body").clone().children()[0].id, "qunit-header", "Make sure cloning body works" );
}); });
test("clone(form element) (Bug #3879, #6655)", function() {
expect(6);
element = jQuery("<select><option>Foo</option><option selected>Bar</option></select>");
equals( element.clone().find("option:selected").val(), element.find("option:selected").val(), "Selected option cloned correctly" );
element = jQuery("<input type='checkbox' value='foo'>").attr('checked', 'checked');
clone = element.clone();
equals( clone.is(":checked"), element.is(":checked"), "Checked input cloned correctly" );
equals( clone[0].defaultValue, "foo", "Checked input defaultValue cloned correctly" );
equals( clone[0].defaultChecked, !jQuery.support.noCloneEvent, "Checked input defaultChecked cloned correctly" );
element = jQuery("<input type='text' value='foo'>");
clone = element.clone();
equals( clone[0].defaultValue, "foo", "Text input defaultValue cloned correctly" );
element = jQuery("<textarea>foo</textarea>");
clone = element.clone();
equals( clone[0].defaultValue, "foo", "Textarea defaultValue cloned correctly" );
});
if (!isLocal) { if (!isLocal) {
test("clone() on XML nodes", function() { test("clone() on XML nodes", function() {
expect(2); expect(2);
...@@ -1232,3 +1261,20 @@ test("jQuery.cleanData", function() { ...@@ -1232,3 +1261,20 @@ test("jQuery.cleanData", function() {
return div; return div;
} }
}); });
test("jQuery.buildFragment - no plain-text caching (Bug #6779)", function() {
expect(1);
// DOM manipulation fails if added text matches an Object method
var $f = jQuery( "<div />" ).appendTo( "#main" ),
bad = [ "start-", "toString", "hasOwnProperty", "append", "here&there!", "-end" ];
for ( var i=0; i < bad.length; i++ ) {
try {
$f.append( bad[i] );
}
catch(e) {}
}
equals($f.text(), bad.join(''), "Cached strings that match Object properties");
$f.remove();
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment