2012-08-12 96 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