2011-09-30 26 views
0

如何獲取應用於數據源的YUI3 sendRequest以返回預定義的對象而不是普通的對象?YUI3返回自定義對象的數據源

例如,我有它的方法該基類:

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屬性的普通對象。然而,我希望這些是學生對象,與他們的成員函數(getId,getName等)

回答

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

}); 
相關問題