EasyUI Forum

General Category => EasyUI for jQuery => Topic started by: devnull on May 22, 2015, 06:52:27 AM



Title: Form Load Object or First Array Element
Post by: devnull on May 22, 2015, 06:52:27 AM
I have a problem with a data source that I cannot control, sometimes it returns and object or sometimes it returns a single element array:

Code:
{ name:'xxx' }

Code:
[{ name:'xxx' }]

Is it possible to extend the form function so that if it is n array it will load the first element if not load the object:

Code:
if(!Array.isArray(data)) return data[0]; else return data;


Title: Re: Form Load Object or First Array Element
Post by: stworthy on May 22, 2015, 05:39:26 PM
Please extend a new method to achieve this functionality.
Code:
$.extend($.fn.form.methods, {
load2: function(jq, data){
return jq.each(function(){
var target = this;
var opts = $(target).data('form').options;
if (typeof data == 'string'){
var param = {};
if (opts.onBeforeLoad.call(target, param) == false) return;

$.ajax({
url: data,
data: param,
dataType: 'json',
success: function(data){
_load(data);
},
error: function(){
opts.onLoadError.apply(target, arguments);
}
});
} else {
_load(data);
}
function _load(data){
if ($.isArray(data)){
data = data[0];
}
$(target).form('load', data);
}
})
}
})

Usage example:
Code:
$('#ff').form('load2', 'get_data.php');
$('#ff').form('load2', [{name: 'xxx}]);
$('#ff').form('load2', {name: 'xxx'});