2013-03-07 26 views
1

我目前正在構建我的第一個Ember.js應用程序。我的問題是返回一個類似jQuery Ajax的響應(異步)到App.PostRoutemodel屬性。我有點困惑,IndexRoute工程和​​沒有。 couchdb.read(doc, callback)將單個對象返回給回調,並且couchdb.view(doc, func, callback)將對象數組返回給回調。我的Ember.js應用程序的主要來源是twbrandt.github.com/2013/02/11/Ember-Quick_Start_Guide使用Ember.js模型與異步jQuery Ajax回調

this.App = Ember.Application.create(); 

    App.Router.map(function() { 
     this.resource('post', { path: '/posts/:post_id' }); 
    }); 
    App.IndexRoute = Ember.Route.extend({ 
     model: function() { 
      return App.Post.newest(); 
     } 
    }); 
    App.PostRoute = Ember.Route.extend({ 
     model: function (parameters) { 
      return App.Post.get(parameters.post_id); 
     } 
    }); 
    App.Post = Ember.Object.extend(); 
    App.Post.reopenClass({ 
     get: function (id) { 
      var post; 
      couchdb.read('post-' + id, function (response) { 
       post = App.Post.create(response); // thanks to mavilein 
      }); // gets a single post by it's id 
      return post; 
     }, 
     newest: function() { 
      var posts = []; 
      couchdb.view('posts', 'all?limit=10&descending=true', function (posts) { 
       posts.forEach(function (post) { 
        posts.addObject(App.Post.create(post)); 
       }, this); 
      }); // loads the 10 newest posts 
      return posts; 
     } 
    }); 

更新:感謝mavilein對他的幫助,現在它工作得更好!但是我只是遇到了無法直接訪問單個帖子頁面的問題(它只顯示默認模板)。我總是必須先訪問索引頁面,然後點擊指向單個帖子頁面的鏈接。這是一個包含我整個代碼的jsFiddle。 jsfiddle.net/dZs2X/2

回答

1

你忘了在get函數中創建一個Post對象(這裏沒有App.Post.create)。

試試這個:

post = App.Post.create(response); 

PS:對不起,壞的格式,但我對智能手機現在:-)

+0

感謝的對你有所幫助,現在它工作得更好,但還不完善。 :)我也用我的HTML創建了一個jsFiddle,mabe這個錯誤在別的地方。 http://jsfiddle.net/dZs2X/2/ – Luis 2013-03-08 18:20:38