move api discovery into its own function

This commit is contained in:
j 2011-12-21 16:24:17 +05:30
parent 734b08d9c6
commit 5168f36053
2 changed files with 79 additions and 50 deletions

View file

@ -0,0 +1,75 @@
// vim: et:ts=4:sw=4:sts=4:ft=javascript
'use strict';
/*@
Ox.Api <o> bin remote api to object
options <o> Options object
timeout <n|60000> request timeout
url <s> request url
callback <f> called once api discover is done
@*/
Ox.Api = function(options, callback) {
var self = {
options: Ox.extend({
timeout: 60000,
type: 'POST',
url: '/api/'
}, options || {}),
time: new Date()
},
that = {
api: function(callback) {
Ox.Request.send({
url: self.options.url,
data: {
action: 'api'
},
callback: callback
});
},
cancel: function(id) {
Ox.Request.cancel(id);
}
};
$.ajaxSetup({
timeout: self.options.timeout,
type: self.options.type,
url: self.options.url
});
/*@
api <o> bakcend API
[action] <f> all api requests available on backend
cancel <f> cancel a request
options <f> get or set options
@*/
that.api(function(result) {
Ox.forEach(result.data.actions, function(val, key) {
that[key] = function(/*data, age, callback*/) {
var data = {}, age = -1, callback = null;
Ox.forEach(arguments, function(argument) {
if (Ox.isObject(argument)) {
data = argument;
} else if (Ox.isNumber(argument)) {
age = argument;
} else if (Ox.isFunction(argument)) {
callback = argument;
}
});
return Ox.Request.send(Ox.extend({
age: age,
callback: callback,
data: {
action: key,
data: JSON.stringify(data)
},
url: self.options.url
}, !val.cache ? {age: 0}: {}));
};
});
callback && callback();
});
return that;
};

View file

@ -20,63 +20,17 @@ Ox.App = function(options) {
options: Ox.extend({
timeout: 60000,
type: 'POST',
url: '/api/',
url: '/api/'
}, options || {}),
time: new Date()
},
that = Ox.Element({}, Ox.extend({}, self));
that.api = {
api: function(callback) {
Ox.Request.send({
url: self.options.url,
data: {
action: 'api'
},
callback: callback
});
},
cancel: function(id) {
Ox.Request.cancel(id);
}
};
$.ajaxSetup({
timeout: self.options.timeout,
that.api = Ox.Api({
type: self.options.type,
timeout: self.options.timeout,
url: self.options.url
});
/*@
api <o> bakcend API
[action] <f> all api requests available on backend
cancel <f> cancel a request
options <f> get or set options
@*/
that.api.api(function(result) {
Ox.forEach(result.data.actions, function(val, key) {
that.api[key] = function(/*data, age, callback*/) {
var data = {}, age = -1, callback = null;
Ox.forEach(arguments, function(argument) {
if (Ox.isObject(argument)) {
data = argument;
} else if (Ox.isNumber(argument)) {
age = argument;
} else if (Ox.isFunction(argument)) {
callback = argument;
}
});
return Ox.Request.send(Ox.extend({
age: age,
callback: callback,
data: {
action: key,
data: JSON.stringify(data)
},
url: self.options.url
}, !val.cache ? {age: 0}: {}));
};
});
}, function() {
that.api.init(getUserData(), function(result) {
//Ox.UI.hideLoadingScreen();
that.triggerEvent({