javascript
- var GUID = function () {
- function S4() {
- return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
- }
- function guid() {
- return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
- }
- return guid();
- };
javascript
- Ajax.Queue = Class.create({
- initialize: function () {
- this.id = GUID();
- this.active = false;
- this.completed = true;
- this.queue = [];
- this.stopped = false;
- Ajax.Queues.push(this);
- },
- add: function (url, options) {
- this.queue.push({ "url": url, "options": options });
- return this.queue.length - 1;
- },
- enqueue: function (url, options) {
- var index = this.add(url, options);
- if (!this.active) this.start();
- return index;
- },
- clear: function () {
- this.queue = [];
- },
- start: function () {
- if (this.queue.length == 0) {
- this.active = false;
- this.completed = true;
- }
- else if (this.stopped) {
- this.stopped = false;
- this.clear();
- this.active = false;
- this.completed = true;
- }
- else {
- this.active = true;
- var params = this.queue.shift();
- params.options = params.options || {};
- var handlers = {
- "Success": function (transport) {
- if (typeof console == "object") console.log("success");
- this.start();
- },
- "Failure": function (transport) {
- if (typeof console == "object") console.log("failure");
- this.active = false;
- },
- "Complete": function (transport) {
- if (typeof console == "object") console.log("complete");
- this.active = false;
- },
- "Exception": function (transport, e) {
- if (typeof console == "object") console.log("exception");
- this.active = false;
- this.exception = e;
- }
- };
- var that = this;
- Object.keys(handlers).each(function (event) {
- var eventName = "on" + event;
- var originalHandler = params.options[eventName];
- var handler = handlers[event];
- params.options[eventName] = (function () {
- if (Object.isFunction(originalHandler)) {
- originalHandler.apply(this, arguments);
- }
- handler.apply(this, arguments);
- }).bind(that);
- });
- this.completed = false;
- new Ajax.Request(params.url, params.options);
- }
- },
- stop: function () {
- this.stopped = true;
- }
- });
- Ajax.Queues = [];
- Ajax.Q = new Ajax.Queue();
usage
- Ajax.Q.enqueue("url", {
- onSuccess: function (transport) {
- try {
- alert(transport.responseText);
- } catch (e) { if(typeof(console) == "object") console.log(e) }
- },
- onFailure: function (ajax) {
- if(typeof(console) == "object") console.log(e);
- }
- });
沒有留言:
張貼留言