0

如何将 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 等)

4

1 回答 1

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);
    }

});
于 2011-09-30T23:29:08.170 回答