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
00041 @implementation CPJSONPConnection : CPObject
00042 {
00043 CPURLRequest _request;
00044 id _delegate;
00045
00046 CPString _callbackParameter;
00047 DOMElement _scriptTag;
00048 }
00049
00051 + (CPJSONPConnection)sendRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate
00052 {
00053 return [self connectionWithRequest:aRequest callback:callbackParameter delegate:aDelegate];
00054 }
00055
00056 + (CPJSONPConnection)connectionWithRequest:(CPURLRequest)aRequest callback:(CPString)callbackParameter delegate:(id)aDelegate
00057 {
00058 return [[[self class] alloc] initWithRequest:aRequest callback:callbackParameter delegate:aDelegate startImmediately:YES];;
00059 }
00060
00061 - (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate
00062 {
00063 return [self initWithRequest:aRequest callback:aString delegate:aDelegate startImmediately: NO];
00064 }
00065
00066 - (id)initWithRequest:(CPURLRequest)aRequest callback:(CPString)aString delegate:(id)aDelegate startImmediately:(BOOL)shouldStartImmediately
00067 {
00068 self = [super init];
00069
00070 _request = aRequest;
00071 _delegate = aDelegate;
00072
00073 _callbackParameter = aString;
00074
00075 CPJSONPConnectionCallbacks["callback"+[self hash]] = function(data)
00076 {
00077 [_delegate connection:self didReceiveData:data];
00078 [self removeScriptTag];
00079
00080 [[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
00081 };
00082
00083 if(shouldStartImmediately)
00084 [self start];
00085
00086 return self;
00087 }
00088
00089 - (void)start
00090 {
00091 try
00092 {
00093 var head = document.getElementsByTagName("head").item(0);
00094
00095 var source = [_request URL];
00096 source += (source.indexOf('?') < 0) ? "?" : "&";
00097 source += _callbackParameter+"=CPJSONPConnectionCallbacks.callback"+[self hash];
00098
00099 _scriptTag = document.createElement("script");
00100 _scriptTag.setAttribute("type", "text/javascript");
00101 _scriptTag.setAttribute("charset", "utf-8");
00102 _scriptTag.setAttribute("src", source);
00103
00104 head.appendChild(_scriptTag);
00105 }
00106 catch (exception)
00107 {
00108 [_delegate connection: self didFailWithError: exception];
00109 [self removeScriptTag];
00110 }
00111 }
00112
00113 - (void)removeScriptTag
00114 {
00115 var head = document.getElementsByTagName("head").item(0);
00116
00117 if(_scriptTag.parentNode == head)
00118 head.removeChild(_scriptTag);
00119
00120 CPJSONPConnectionCallbacks["callback"+[self hash]] = nil;
00121 delete CPJSONPConnectionCallbacks["callback"+[self hash]];
00122 }
00123
00124 - (void)cancel
00125 {
00126 [self removeScriptTag];
00127 }
00128
00129 @end