如何将YUI3 sendRequest应用于数据源以返回预定义对象而不是普通对象?
例如,我有这个Base类及其方法:
function Student(id, name){
this.id = id;
this.name = name;
}
Context.prototype.setId = function(id){ this.id = id; };
Context.prototype.setName = function(name){ this.name = name; };
Context.prototype.getId = function(){ return this.id; };
Context.prototype.getName = function(){ return this.name; };
我有这个代码从API检索数据,规范化它并将数据作为对象返回:
var studApiDataSource = new Y.DataSource.Get({source: API_URL});
studApiDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "response.student",
resultFields: ["id","name"]
}
});
var myCallback = function(e) {
Y.Array.each(e.response.results, function(stud){
Y.log(stud.id+' '+stud.name);
}
}
studApiDataSource.sendRequest({
request: "?cmd=getStudents",
callback: {
success: myCallback,
failure: function (e) { }
}
});
studApiDataSource.sendRequest()检索并传递给myCallback的对象数组是普通对象,具有id和name属性。但是,我希望它们是Student对象,它们的成员函数也是(getId,getName等)
答案 0 :(得分:1)
我不确定我是否完全明白,但你可以做以下事情。
var studentJSON = "{\"id\": 17, \"name\":\"my name is\"}";
function Student(obj){
this.name = obj.name;
this.id = obj.id;
}
Student.prototype.setId = function(id){ this.id = id; };
Student.prototype.setName = function(name){ this.name = name; };
Student.prototype.getId = function(){ return this.id; };
Student.prototype.getName = function(){ return this.name; };
YUI().use('json-parse', 'json-stringify', function (Y) {
try {
var stud = new Student(Y.JSON.parse(studentJSON));
alert(stud.getId());
}
catch (e) {
alert(e);
}
});