push.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. function Push(options) {
  2. this.doNotConnect = 0;
  3. options = options || {};
  4. options.heartbeat = options.heartbeat || 25000;
  5. options.pingTimeout = options.pingTimeout || 10000;
  6. this.config = options;
  7. this.uid = 0;
  8. this.channels = {};
  9. this.connection = null;
  10. this.pingTimeoutTimer = 0;
  11. Push.instances.push(this);
  12. this.createConnection();
  13. }
  14. Push.prototype.checkoutPing = function() {
  15. var _this = this;
  16. _this.checkoutPingTimer && clearTimeout(_this.checkoutPingTimer);
  17. _this.checkoutPingTimer = setTimeout(function () {
  18. _this.checkoutPingTimer = 0;
  19. if (_this.connection.state === 'connected') {
  20. _this.connection.send('{"event":"pusher:ping","data":{}}');
  21. if (_this.pingTimeoutTimer) {
  22. clearTimeout(_this.pingTimeoutTimer);
  23. _this.pingTimeoutTimer = 0;
  24. }
  25. _this.pingTimeoutTimer = setTimeout(function () {
  26. _this.connection.closeAndClean();
  27. if (!_this.connection.doNotConnect) {
  28. _this.connection.waitReconnect();
  29. }
  30. }, _this.config.pingTimeout);
  31. }
  32. }, this.config.heartbeat);
  33. };
  34. Push.prototype.channel = function (name) {
  35. return this.channels.find(name);
  36. };
  37. Push.prototype.allChannels = function () {
  38. return this.channels.all();
  39. };
  40. Push.prototype.createConnection = function () {
  41. if (this.connection) {
  42. throw Error('Connection already exist');
  43. }
  44. var _this = this;
  45. var url = this.config.url;
  46. function updateSubscribed () {
  47. for (var i in _this.channels) {
  48. _this.channels[i].subscribed = false;
  49. }
  50. }
  51. this.connection = new Connection({
  52. url: url,
  53. app_key: this.config.app_key,
  54. onOpen: function () {
  55. _this.connection.state = 'connecting';
  56. _this.checkoutPing();
  57. },
  58. onMessage: function(params) {
  59. if(_this.pingTimeoutTimer) {
  60. clearTimeout(_this.pingTimeoutTimer);
  61. _this.pingTimeoutTimer = 0;
  62. }
  63. params = JSON.parse(params.data);
  64. var event = params.event;
  65. var channel_name = params.channel;
  66. if (event === 'pusher:pong') {
  67. _this.checkoutPing();
  68. return;
  69. }
  70. if (event === 'pusher:error') {
  71. throw Error(params.data.message);
  72. }
  73. var data = JSON.parse(params.data), channel;
  74. if (event === 'pusher_internal:subscription_succeeded') {
  75. channel = _this.channels[channel_name];
  76. channel.subscribed = true;
  77. channel.processQueue();
  78. channel.emit('pusher:subscription_succeeded');
  79. return;
  80. }
  81. if (event === 'pusher:connection_established') {
  82. _this.connection.socket_id = data.socket_id;
  83. _this.connection.updateNetworkState('connected');
  84. _this.subscribeAll();
  85. }
  86. if (event.indexOf('pusher_internal') !== -1) {
  87. console.log("Event '"+event+"' not implement");
  88. return;
  89. }
  90. channel = _this.channels[channel_name];
  91. if (channel) {
  92. channel.emit(event, data);
  93. }
  94. },
  95. onClose: function () {
  96. updateSubscribed();
  97. },
  98. onError: function () {
  99. updateSubscribed();
  100. }
  101. });
  102. };
  103. Push.prototype.disconnect = function () {
  104. this.connection.doNotConnect = 1;
  105. this.connection.close();
  106. };
  107. Push.prototype.subscribeAll = function () {
  108. if (this.connection.state !== 'connected') {
  109. return;
  110. }
  111. for (var channel_name in this.channels) {
  112. //this.connection.send(JSON.stringify({event:"pusher:subscribe", data:{channel:channel_name}}));
  113. this.channels[channel_name].processSubscribe();
  114. }
  115. };
  116. Push.prototype.unsubscribe = function (channel_name) {
  117. if (this.channels[channel_name]) {
  118. delete this.channels[channel_name];
  119. if (this.connection.state === 'connected') {
  120. this.connection.send(JSON.stringify({event:"pusher:unsubscribe", data:{channel:channel_name}}));
  121. }
  122. }
  123. };
  124. Push.prototype.unsubscribeAll = function () {
  125. var channels = Object.keys(this.channels);
  126. if (channels.length) {
  127. if (this.connection.state === 'connected') {
  128. for (var channel_name in this.channels) {
  129. this.unsubscribe(channel_name);
  130. }
  131. }
  132. }
  133. this.channels = {};
  134. };
  135. Push.prototype.subscribe = function (channel_name) {
  136. if (this.channels[channel_name]) {
  137. return this.channels[channel_name];
  138. }
  139. if (channel_name.indexOf('private-') === 0) {
  140. return createPrivateChannel(channel_name, this);
  141. }
  142. if (channel_name.indexOf('presence-') === 0) {
  143. return createPresenceChannel(channel_name, this);
  144. }
  145. return createChannel(channel_name, this);
  146. };
  147. Push.instances = [];
  148. function createChannel(channel_name, push)
  149. {
  150. var channel = new Channel(push.connection, channel_name);
  151. push.channels[channel_name] = channel;
  152. channel.subscribeCb = function () {
  153. push.connection.send(JSON.stringify({event:"pusher:subscribe", data:{channel:channel_name}}));
  154. }
  155. channel.processSubscribe();
  156. return channel;
  157. }
  158. function createPrivateChannel(channel_name, push)
  159. {
  160. var channel = new Channel(push.connection, channel_name);
  161. push.channels[channel_name] = channel;
  162. channel.subscribeCb = function () {
  163. __ajax({
  164. url: push.config.auth,
  165. type: 'POST',
  166. data: {channel_name: channel_name, socket_id: push.connection.socket_id},
  167. success: function (data) {
  168. data = JSON.parse(data);
  169. data.channel = channel_name;
  170. push.connection.send(JSON.stringify({event:"pusher:subscribe", data:data}));
  171. },
  172. error: function (e) {
  173. throw Error(e);
  174. }
  175. });
  176. };
  177. channel.processSubscribe();
  178. return channel;
  179. }
  180. function createPresenceChannel(channel_name, push)
  181. {
  182. return createPrivateChannel(channel_name, push);
  183. }
  184. uni.onNetworkStatusChange(function (res) {
  185. if(res.isConnected) {
  186. for (var i in Push.instances) {
  187. var con = Push.instances[i].connection;
  188. con.reconnectInterval = 1;
  189. if (con.state === 'connecting') {
  190. con.connect();
  191. }
  192. }
  193. }
  194. });
  195. function Connection(options) {
  196. this.dispatcher = new Dispatcher();
  197. __extends(this, this.dispatcher);
  198. var properies = ['on', 'off', 'emit'];
  199. for (var i in properies) {
  200. this[properies[i]] = this.dispatcher[properies[i]];
  201. }
  202. this.options = options;
  203. this.state = 'initialized'; //initialized connecting connected disconnected
  204. this.doNotConnect = 0;
  205. this.reconnectInterval = 1;
  206. this.connection = null;
  207. this.reconnectTimer = 0;
  208. this.connect();
  209. }
  210. Connection.prototype.updateNetworkState = function(state){
  211. var old_state = this.state;
  212. this.state = state;
  213. if (old_state !== state) {
  214. this.emit('state_change', { previous: old_state, current: state });
  215. }
  216. };
  217. Connection.prototype.connect = function () {
  218. this.doNotConnect = 0;
  219. if (this.networkState == 'connecting' || this.networkState == 'established') {
  220. console.log('networkState is ' + this.networkState + ' and do not need connect');
  221. return;
  222. }
  223. if (this.reconnectTimer) {
  224. clearTimeout(this.reconnectTimer);
  225. this.reconnectTimer = 0;
  226. }
  227. this.closeAndClean();
  228. var options = this.options;
  229. var _this = this;
  230. _this.updateNetworkState('connecting');
  231. var cb = function(){
  232. uni.onSocketOpen(function (res) {
  233. _this.reconnectInterval = 1;
  234. if (_this.doNotConnect) {
  235. _this.updateNetworkState('closing');
  236. uni.closeSocket();
  237. return;
  238. }
  239. _this.updateNetworkState('established');
  240. if (options.onOpen) {
  241. options.onOpen(res);
  242. }
  243. });
  244. if (options.onMessage) {
  245. uni.onSocketMessage(options.onMessage);
  246. }
  247. uni.onSocketClose(function (res) {
  248. _this.updateNetworkState('disconnected');
  249. if (!_this.doNotConnect) {
  250. _this.waitReconnect();
  251. }
  252. if (options.onClose) {
  253. options.onClose(res);
  254. }
  255. });
  256. uni.onSocketError(function (res) {
  257. _this.close();
  258. if (!_this.doNotConnect) {
  259. _this.waitReconnect();
  260. }
  261. if (options.onError) {
  262. options.onError(res);
  263. }
  264. });
  265. };
  266. uni.connectSocket({
  267. url: options.url,
  268. fail: function (res) {
  269. console.log('uni.connectSocket fail');
  270. console.log(res);
  271. _this.updateNetworkState('disconnected');
  272. _this.waitReconnect();
  273. },
  274. success: function() {
  275. }
  276. });
  277. cb();
  278. }
  279. Connection.prototype.connect = function () {
  280. this.doNotConnect = 0;
  281. if (this.state === 'connected') {
  282. console.log('networkState is "' + this.state + '" and do not need connect');
  283. return;
  284. }
  285. if (this.reconnectTimer) {
  286. clearTimeout(this.reconnectTimer);
  287. this.reconnectTimer = 0;
  288. }
  289. this.closeAndClean();
  290. var options = this.options;
  291. this.updateNetworkState('connecting');
  292. var _this = this;
  293. var cb = function(){
  294. uni.onSocketOpen(function (res) {
  295. _this.reconnectInterval = 1;
  296. if (_this.doNotConnect) {
  297. _this.updateNetworkState('disconnected');
  298. uni.closeSocket();
  299. return;
  300. }
  301. if (options.onOpen) {
  302. options.onOpen(res);
  303. }
  304. });
  305. if (options.onMessage) {
  306. uni.onSocketMessage(options.onMessage);
  307. }
  308. uni.onSocketClose(function (res) {
  309. _this.updateNetworkState('disconnected');
  310. if (!_this.doNotConnect) {
  311. _this.waitReconnect();
  312. }
  313. if (options.onClose) {
  314. options.onClose(res);
  315. }
  316. });
  317. uni.onSocketError(function (res) {
  318. _this.close();
  319. if (!_this.doNotConnect) {
  320. _this.waitReconnect();
  321. }
  322. if (options.onError) {
  323. options.onError(res);
  324. }
  325. });
  326. };
  327. uni.connectSocket({
  328. url: options.url+'/app/'+options.app_key,
  329. fail: function (res) {
  330. console.log('uni.connectSocket fail');
  331. console.log(res);
  332. _this.updateNetworkState('disconnected');
  333. _this.waitReconnect();
  334. },
  335. success: function() {
  336. }
  337. });
  338. cb();
  339. }
  340. Connection.prototype.closeAndClean = function () {
  341. if (this.state === 'connected') {
  342. uni.closeSocket();
  343. }
  344. this.updateNetworkState('disconnected');
  345. };
  346. Connection.prototype.waitReconnect = function () {
  347. if (this.state === 'connected' || this.state === 'connecting') {
  348. return;
  349. }
  350. if (!this.doNotConnect) {
  351. this.updateNetworkState('connecting');
  352. var _this = this;
  353. if (this.reconnectTimer) {
  354. clearTimeout(this.reconnectTimer);
  355. }
  356. this.reconnectTimer = setTimeout(function(){
  357. _this.connect();
  358. }, this.reconnectInterval);
  359. if (this.reconnectInterval < 1000) {
  360. this.reconnectInterval = 1000;
  361. } else {
  362. // 每次重连间隔增大一倍
  363. this.reconnectInterval = this.reconnectInterval * 2;
  364. }
  365. // 有网络的状态下,重连间隔最大2秒
  366. if (this.reconnectInterval > 2000) {
  367. uni.getNetworkType({
  368. success: function (res) {
  369. if (res.networkType != 'none') {
  370. _this.reconnectInterval = 1000;
  371. }
  372. }
  373. });
  374. }
  375. }
  376. }
  377. Connection.prototype.send = function(data) {
  378. if (this.state !== 'connected') {
  379. console.trace('networkState is "' + this.state + '", can not send ' + data);
  380. return;
  381. }
  382. uni.sendSocketMessage({
  383. data: data
  384. });
  385. }
  386. Connection.prototype.close = function(){
  387. this.updateNetworkState('disconnected');
  388. uni.closeSocket();
  389. }
  390. var __extends = (this && this.__extends) || function (d, b) {
  391. for (var p in b) if (b.hasOwnProperty(p)) {d[p] = b[p];}
  392. function __() { this.constructor = d; }
  393. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  394. };
  395. function Channel(connection, channel_name) {
  396. this.subscribed = false;
  397. this.dispatcher = new Dispatcher();
  398. this.connection = connection;
  399. this.channelName = channel_name;
  400. this.subscribeCb = null;
  401. this.queue = [];
  402. __extends(this, this.dispatcher);
  403. var properies = ['on', 'off', 'emit'];
  404. for (var i in properies) {
  405. this[properies[i]] = this.dispatcher[properies[i]];
  406. }
  407. }
  408. Channel.prototype.processSubscribe = function () {
  409. if (this.connection.state !== 'connected') {
  410. return;
  411. }
  412. this.subscribeCb();
  413. };
  414. Channel.prototype.processQueue = function () {
  415. if (this.connection.state !== 'connected' || !this.subscribed) {
  416. return;
  417. }
  418. for (var i in this.queue) {
  419. this.queue[i]();
  420. }
  421. this.queue = [];
  422. };
  423. Channel.prototype.trigger = function (event, data) {
  424. if (event.indexOf('client-') !== 0) {
  425. throw new Error("Event '" + event + "' should start with 'client-'");
  426. }
  427. var _this = this;
  428. this.queue.push(function () {
  429. _this.connection.send(JSON.stringify({ event: event, data: data, channel: _this.channelName }));
  430. });
  431. this.processQueue();
  432. };
  433. ////////////////
  434. var Collections = (function () {
  435. var exports = {};
  436. function extend(target) {
  437. var sources = [];
  438. for (var _i = 1; _i < arguments.length; _i++) {
  439. sources[_i - 1] = arguments[_i];
  440. }
  441. for (var i = 0; i < sources.length; i++) {
  442. var extensions = sources[i];
  443. for (var property in extensions) {
  444. if (extensions[property] && extensions[property].constructor &&
  445. extensions[property].constructor === Object) {
  446. target[property] = extend(target[property] || {}, extensions[property]);
  447. }
  448. else {
  449. target[property] = extensions[property];
  450. }
  451. }
  452. }
  453. return target;
  454. }
  455. exports.extend = extend;
  456. function stringify() {
  457. var m = ["Push"];
  458. for (var i = 0; i < arguments.length; i++) {
  459. if (typeof arguments[i] === "string") {
  460. m.push(arguments[i]);
  461. }
  462. else {
  463. m.push(safeJSONStringify(arguments[i]));
  464. }
  465. }
  466. return m.join(" : ");
  467. }
  468. exports.stringify = stringify;
  469. function arrayIndexOf(array, item) {
  470. var nativeIndexOf = Array.prototype.indexOf;
  471. if (array === null) {
  472. return -1;
  473. }
  474. if (nativeIndexOf && array.indexOf === nativeIndexOf) {
  475. return array.indexOf(item);
  476. }
  477. for (var i = 0, l = array.length; i < l; i++) {
  478. if (array[i] === item) {
  479. return i;
  480. }
  481. }
  482. return -1;
  483. }
  484. exports.arrayIndexOf = arrayIndexOf;
  485. function objectApply(object, f) {
  486. for (var key in object) {
  487. if (Object.prototype.hasOwnProperty.call(object, key)) {
  488. f(object[key], key, object);
  489. }
  490. }
  491. }
  492. exports.objectApply = objectApply;
  493. function keys(object) {
  494. var keys = [];
  495. objectApply(object, function (_, key) {
  496. keys.push(key);
  497. });
  498. return keys;
  499. }
  500. exports.keys = keys;
  501. function values(object) {
  502. var values = [];
  503. objectApply(object, function (value) {
  504. values.push(value);
  505. });
  506. return values;
  507. }
  508. exports.values = values;
  509. function apply(array, f, context) {
  510. for (var i = 0; i < array.length; i++) {
  511. f.call(context || (window), array[i], i, array);
  512. }
  513. }
  514. exports.apply = apply;
  515. function map(array, f) {
  516. var result = [];
  517. for (var i = 0; i < array.length; i++) {
  518. result.push(f(array[i], i, array, result));
  519. }
  520. return result;
  521. }
  522. exports.map = map;
  523. function mapObject(object, f) {
  524. var result = {};
  525. objectApply(object, function (value, key) {
  526. result[key] = f(value);
  527. });
  528. return result;
  529. }
  530. exports.mapObject = mapObject;
  531. function filter(array, test) {
  532. test = test || function (value) {
  533. return !!value;
  534. };
  535. var result = [];
  536. for (var i = 0; i < array.length; i++) {
  537. if (test(array[i], i, array, result)) {
  538. result.push(array[i]);
  539. }
  540. }
  541. return result;
  542. }
  543. exports.filter = filter;
  544. function filterObject(object, test) {
  545. var result = {};
  546. objectApply(object, function (value, key) {
  547. if ((test && test(value, key, object, result)) || Boolean(value)) {
  548. result[key] = value;
  549. }
  550. });
  551. return result;
  552. }
  553. exports.filterObject = filterObject;
  554. function flatten(object) {
  555. var result = [];
  556. objectApply(object, function (value, key) {
  557. result.push([key, value]);
  558. });
  559. return result;
  560. }
  561. exports.flatten = flatten;
  562. function any(array, test) {
  563. for (var i = 0; i < array.length; i++) {
  564. if (test(array[i], i, array)) {
  565. return true;
  566. }
  567. }
  568. return false;
  569. }
  570. exports.any = any;
  571. function all(array, test) {
  572. for (var i = 0; i < array.length; i++) {
  573. if (!test(array[i], i, array)) {
  574. return false;
  575. }
  576. }
  577. return true;
  578. }
  579. exports.all = all;
  580. function encodeParamsObject(data) {
  581. return mapObject(data, function (value) {
  582. if (typeof value === "object") {
  583. value = safeJSONStringify(value);
  584. }
  585. return encodeURIComponent(base64_1["default"](value.toString()));
  586. });
  587. }
  588. exports.encodeParamsObject = encodeParamsObject;
  589. function buildQueryString(data) {
  590. var params = filterObject(data, function (value) {
  591. return value !== undefined;
  592. });
  593. return map(flatten(encodeParamsObject(params)), util_1["default"].method("join", "=")).join("&");
  594. }
  595. exports.buildQueryString = buildQueryString;
  596. function decycleObject(object) {
  597. var objects = [], paths = [];
  598. return (function derez(value, path) {
  599. var i, name, nu;
  600. switch (typeof value) {
  601. case 'object':
  602. if (!value) {
  603. return null;
  604. }
  605. for (i = 0; i < objects.length; i += 1) {
  606. if (objects[i] === value) {
  607. return {$ref: paths[i]};
  608. }
  609. }
  610. objects.push(value);
  611. paths.push(path);
  612. if (Object.prototype.toString.apply(value) === '[object Array]') {
  613. nu = [];
  614. for (i = 0; i < value.length; i += 1) {
  615. nu[i] = derez(value[i], path + '[' + i + ']');
  616. }
  617. }
  618. else {
  619. nu = {};
  620. for (name in value) {
  621. if (Object.prototype.hasOwnProperty.call(value, name)) {
  622. nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']');
  623. }
  624. }
  625. }
  626. return nu;
  627. case 'number':
  628. case 'string':
  629. case 'boolean':
  630. return value;
  631. }
  632. }(object, '$'));
  633. }
  634. exports.decycleObject = decycleObject;
  635. function safeJSONStringify(source) {
  636. try {
  637. return JSON.stringify(source);
  638. }
  639. catch (e) {
  640. return JSON.stringify(decycleObject(source));
  641. }
  642. }
  643. exports.safeJSONStringify = safeJSONStringify;
  644. return exports;
  645. })();
  646. var Dispatcher = (function () {
  647. function Dispatcher(failThrough) {
  648. this.callbacks = new CallbackRegistry();
  649. this.global_callbacks = [];
  650. this.failThrough = failThrough;
  651. }
  652. Dispatcher.prototype.on = function (eventName, callback, context) {
  653. this.callbacks.add(eventName, callback, context);
  654. return this;
  655. };
  656. Dispatcher.prototype.on_global = function (callback) {
  657. this.global_callbacks.push(callback);
  658. return this;
  659. };
  660. Dispatcher.prototype.off = function (eventName, callback, context) {
  661. this.callbacks.remove(eventName, callback, context);
  662. return this;
  663. };
  664. Dispatcher.prototype.emit = function (eventName, data) {
  665. var i;
  666. for (i = 0; i < this.global_callbacks.length; i++) {
  667. this.global_callbacks[i](eventName, data);
  668. }
  669. var callbacks = this.callbacks.get(eventName);
  670. if (callbacks && callbacks.length > 0) {
  671. for (i = 0; i < callbacks.length; i++) {
  672. callbacks[i].fn.call(callbacks[i].context || (window), data);
  673. }
  674. }
  675. else if (this.failThrough) {
  676. this.failThrough(eventName, data);
  677. }
  678. return this;
  679. };
  680. return Dispatcher;
  681. }());
  682. var CallbackRegistry = (function () {
  683. function CallbackRegistry() {
  684. this._callbacks = {};
  685. }
  686. CallbackRegistry.prototype.get = function (name) {
  687. return this._callbacks[prefix(name)];
  688. };
  689. CallbackRegistry.prototype.add = function (name, callback, context) {
  690. var prefixedEventName = prefix(name);
  691. this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || [];
  692. this._callbacks[prefixedEventName].push({
  693. fn: callback,
  694. context: context
  695. });
  696. };
  697. CallbackRegistry.prototype.remove = function (name, callback, context) {
  698. if (!name && !callback && !context) {
  699. this._callbacks = {};
  700. return;
  701. }
  702. var names = name ? [prefix(name)] : Collections.keys(this._callbacks);
  703. if (callback || context) {
  704. this.removeCallback(names, callback, context);
  705. }
  706. else {
  707. this.removeAllCallbacks(names);
  708. }
  709. };
  710. CallbackRegistry.prototype.removeCallback = function (names, callback, context) {
  711. Collections.apply(names, function (name) {
  712. this._callbacks[name] = Collections.filter(this._callbacks[name] || [], function (oning) {
  713. return (callback && callback !== oning.fn) ||
  714. (context && context !== oning.context);
  715. });
  716. if (this._callbacks[name].length === 0) {
  717. delete this._callbacks[name];
  718. }
  719. }, this);
  720. };
  721. CallbackRegistry.prototype.removeAllCallbacks = function (names) {
  722. Collections.apply(names, function (name) {
  723. delete this._callbacks[name];
  724. }, this);
  725. };
  726. return CallbackRegistry;
  727. }());
  728. function prefix(name) {
  729. return "_" + name;
  730. }
  731. function __ajax(options){
  732. options=options||{};
  733. options.type=(options.type||'GET').toUpperCase();
  734. options.dataType=options.dataType||'json';
  735. var params=formatParams(options.data);
  736. var xhr;
  737. if(window.XMLHttpRequest){
  738. xhr=new XMLHttpRequest();
  739. }else{
  740. xhr=ActiveXObject('Microsoft.XMLHTTP');
  741. }
  742. xhr.onreadystatechange=function(){
  743. if(xhr.readyState === 4){
  744. var status=xhr.status;
  745. if(status>=200 && status<300){
  746. options.success&&options.success(xhr.responseText,xhr.responseXML);
  747. }else{
  748. options.error&&options.error(status);
  749. }
  750. }
  751. }
  752. if(options.type==='GET'){
  753. xhr.open('GET',options.url+'?'+params,true);
  754. xhr.send(null);
  755. }else if(options.type==='POST'){
  756. xhr.open('POST',options.url,true);
  757. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  758. xhr.send(params);
  759. }
  760. }
  761. function formatParams(data){
  762. var arr=[];
  763. for(var name in data){
  764. arr.push(encodeURIComponent(name)+'='+encodeURIComponent(data[name]));
  765. }
  766. return arr.join('&');
  767. }
  768. export default Push