2014-02-13 51 views
1

我有一個路由爲#/ 0,#/ 1,#/ 2這加載相應的模板時單擊用戶名稱。 但是當我點擊用戶名下面的錯誤被拋出,Ember.js動態路由器不加載模板使用序列化

Error while loading route: TypeError: Object # has no method 'addArrayObserver'

但是,當我直接訪問該網址本地主機:8080/dynam.html#/ 0,我得到的輸出,

25

模板:

<script type="text/x-handlebars" data-template-name="application"> 
    {{outlet}} 
    </script> 

    <script type="text/x-handlebars" data-template-name="index"> 
    <h2>Names</h2> 
    <ul> 
    {{#each model}} 
     <li>{{#linkTo "test" this}}{{this.firstName}} {{this.lastName}}{{/linkTo}}</li> 
    {{/each}} 
    </ul> 
    </script> 

    <script type="text/x-handlebars" data-template-name="test"> 
    <h2>Item Loaded</h2> 
    {{#each model}} 
     <li>{{#linkTo "test" this}} {{Age}} {{/linkTo}}</li> 
    {{/each}} 
    </script> 

App.js:

App = Ember.Application.create({}); 

App.Router.map(function() { 
    this.route('test', {path: '/:id'}); 
}); 

App.IndexRoute = Ember.Route.extend({ 
    model: function(id){ 
     return [ 
       {id: 0, firstName: 'Kris', lastName: 'Selden'}, 
       {id: 1, firstName: 'Luke', lastName: 'Melia'}, 
       {id: 2, firstName: 'Formerly Alex', lastName: 'Matchneer'} 
      ]; 
    }, 
    serialize: function(model) { 
    return {id: model.id}; 
    }       
}); 

App.TestRoute = Ember.Route.extend({ 
    model: function(){ 
    return App.TestObj.getArray(); 
    } 
}); 

App.TestObj = Ember.Object.extend(); 
App.TestObj.reopenClass({ 
    testArr : [ {Age: '26' } ], 
    test1Arr : [], 
    getArray : function(){ 
    this.testArr.forEach(function(obj){ 
      this.test1Arr.pushObject(App.TestObj.create(obj)); 
     }, this); 
    return this.test1Arr; 
    } 

}) 

回答

0

當經由

{{#link-to routname model}} 

進入的串行化路由示範鉤將不會被運行。相反,該模型由您在{{#link-to}}助手中設置的任何輸入值設置。

所以在你的代碼已經編寫,當你點擊

{{#linkTo "test" this}} 

您正在進入「測試」的路線,並設定模型你點擊任何人。例如,如果您選擇的第一人,你會設置TestRoute到模型:

{id: 0, firstName: 'Kris', lastName: 'Selden'} 

現在你呈現你的測試模板,其中包括{{#each模型}}幫手......但你的模型只有一個對象,所以它無法正常運行。

另一方面,當您直接使用url輸入路線時,模型掛鉤將會運行。這就是爲什麼你以這種方式運行時獲得年齡值的原因。

通常,對於序列化路徑,您應該使用模型掛鉤來檢索默認情況下通常會傳入的信息。例如:

model: function(param){ 
    var id = param.id; //This will return the serialized portion of your url 
    return someFunction(id); //Use that serialized value to look up the correct model 
} 
+0

感謝您的回覆。我應該在哪裏使用返回「someFunction(id)」的模型,在IndexRoute或TestRoute中,我的模型的結構應該是什麼。 – Jeevi

+0

你的模型結構應該是任何必要的。沒有黃金標準,它只是您需要的相關信息的傾銷地。 – gravityplanx