2012-08-12 92 views
3

在不斷變化的Ember.js世界中,我正在尋找一些幫助獲得簡單的應用程序並運行。基本Ember.js路由和數據加載

我想獲得一些基本的框架下來通過JSON加載數據通過API與Ember.js,但無法獲取數據出現。該代碼可以在這裏找到:

var App = Ember.Application.create(); 

App.ApplicationController = Ember.Controller.extend(); 
App.ApplicationView = Ember.View.extend({ 
    templateName: 'application' 
}); 

App.Movie = Ember.Object.extend({ 
    title: null, 
    rating: null, 
    release_date: null, 
    poster_image: null 
}); 

App.MoviesView = Ember.View.extend({ 
    templateName: 'movie-list' 
}); 

App.moviesController = Ember.ArrayController.create({ 
    content: [], 
    init: function(){ 
     var me = this; 
     $.getJSON('/trailers/api/movies',function(data){ 
      me.set('content', []); 
      $(data.movies).each(function(index,value){ 
       var t = App.Movie.create({ 
        title: value.title, 
        rating: value.rating, 
        release_date: value.release_date, 
        poster_image: value.poster_image 
       }); 
       me.pushObject(t); 
      }) 
     }); 
    } 
}); 

App.router = Ember.Router.create({ 
    enableLogging: true, 
    root: Ember.Route.extend({ 
     index: Ember.Route.extend({ 
      route: '/', 
      redirectsTo: 'movies' 
     }), 
     movies: Ember.Route.extend({ 
      route: '/movies', 
      connectOutlets: function(router) { 
       return router.get('applicationController').connectOutlet({ 
       viewClass: App.MoviesView, 
       controller: App.moviesController 
       }); 
      } 
     }) 
    }) 
}); 

App.initialize(App.router); 
<script type="text/x-handlebars" data-template-name="application"> 
    <h1>Application</h1> 
    {{outlet}} 
</script> 

<script type="text/x-handlebars" data-template-name="movie-list"> 
    <h2>Movie List</h2> 
    <ul> 
    {{#each App.movieController}} 
    <li><a {{action showMovie context="movie" href=true}}>{{title}}</a></li> 
    {{/each}} 
    </ul> 
</script> 

http://jsfiddle.net/qmZrT/

模板加載正確的,因爲我可以看到「應用程序」和「電影榜」頭,但無序列表中沒有填充數據。

我沒有在控制檯中發現任何錯誤,XML請求被正確返回,如果我鍵入App.movi​​esController.content,我得到一個「Class」es數組,它似乎包含來自我的API的數據。

任何人都可以提供任何想法或指導?

回答

5

有你的腳本

  1. 爲了你裝載庫的幾個問題:灰燼取決於車把,所以它必須灰燼被加載。我已經改變了順序。
  2. {{action}}幫助程序已更改以支持多個上下文:請參閱this。你也試圖迭代moviesController的實例,但由於你使用的是Router,你應該簡單地遍歷controller,它在connectOutlets中注入了moviesController
  3. 您的AJAX調用將永遠不會在JSFiddle上工作,原因很明顯:您指向的URL位於您的環境中,並且您無法通過JSFiddle訪問該URL。我已經手動添加了數據到您的收藏集,以便您看到正在運行的內容

這是你的代碼的修改版本:JSFiddle Demo

編輯

不像在這個問題說,你在控制檯中看到的錯誤:

Uncaught Error: <.ApplicationView:ember158> - Unable to find template "application".

這自從t開始,斷言幫助我找到了添加腳本(句柄和ember)的順序的問題他的模板名稱是正確的,這意味着它與視圖中指定的名稱相匹配,所以問題必須在其他地方。我注意到在JSFiddle的「管理資源」選項卡中,你已經將Ember加載到Handlebars之前,並且它有很大的不同。

+0

太棒了!像魅力一樣工作。非常感謝你的幫助。 – 2012-08-12 21:55:56

+0

歡迎,我很高興這有幫助 – MilkyWayJoe 2012-08-13 13:19:29