oxjs/source/Ox.UI/js/Core/API.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

'use strict';
2012-05-21 10:38:18 +00:00
/*@
2012-05-22 13:14:40 +00:00
Ox.API <f> bind 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
@*/
2011-12-21 15:42:11 +00:00
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,
2011-12-30 09:33:01 +00:00
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) {
2012-05-25 17:46:02 +00:00
var type = Ox.typeOf(argument);
if (type == 'object') {
data = argument;
2012-05-25 17:46:02 +00:00
} else if (type == 'number') {
age = argument;
2012-05-25 17:46:02 +00:00
} else if (type == 'function') {
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;
};