00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 @import <Foundation/CPObject.j>
00024
00025
00026 CPJSONPConnectionCallbacks = {};
00027
00037 @implementation CPJSONPConnection : CPObject
00038 {
00039 CPURLRequest _request;
00040 id _delegate;
00041
00042 CPString _callbackParameter;
00043 DOMElement _scriptTag;
00044 }
00045
00047 + (CPJSONPConnection)sendRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate
00048 {
00049 return [self connectionWithRequest:aRequest callback:callbackParameter delegate:aDelegate];
00050 }
00051
00052 + (CPJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate
00053 {
00054 return [[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate startImmediately:YES];;
00055 }
00056
00057 - (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate
00058 {
00059 return [self initWithRequest:aRequest callback:aString delegate:aDelegate startImmediately: NO];
00060 }
00061
00062 - (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately
00063 {
00064 self = [super init];
00065
00066 _request = aRequest;
00067 _delegate = aDelegate;
00068
00069 _callbackParameter = aString;
00070
00071 CPJSONPConnectionCallbacks["callback"+[self hash]] = function(data)
00072 {
00073 [_delegate connection:self didReceiveData:data];
00074 [self removeScriptTag];
00075
00076 [[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
00077 };
00078
00079 if(shouldStartImmediately)
00080 [self start];
00081
00082 return self;
00083 }
00084
00085 - (void)start
00086 {
00087 try
00088 {
00089 var head = document.getElementsByTagName("head").item(0);
00090
00091 var source = [_request URL];
00092 source += (source.indexOf('?') < 0) ? "?" : "&";
00093 source += _callbackParameter+"=CPJSONPConnectionCallbacks.callback"+[self hash];
00094
00095 _scriptTag = document.createElement("script");
00096 _scriptTag.setAttribute("type", "text/javascript");
00097 _scriptTag.setAttribute("charset", "utf-8");
00098 _scriptTag.setAttribute("src", source);
00099
00100 head.appendChild(_scriptTag);
00101 }
00102 catch (exception)
00103 {
00104 [_delegate connection: self didFailWithError: exception];
00105 [self removeScriptTag];
00106 }
00107 }
00108
00109 - (void)removeScriptTag
00110 {
00111 var head = document.getElementsByTagName("head").item(0);
00112
00113 if(_scriptTag.parentNode == head)
00114 head.removeChild(_scriptTag);
00115
00116 CPJSONPConnectionCallbacks["callback"+[self hash]] = nil;
00117 delete CPJSONPConnectionCallbacks["callback"+[self hash]];
00118 }
00119
00120 - (void)cancel
00121 {
00122 [self removeScriptTag];
00123 }
00124
00125 @end