Reputation: 77
I am making an app using OMDB api. I have define a method 'top_movies' in 'movie_controller' which is rendering json data.
I have defined collection like this:
class Fanboy.Collections.Movies extends Backbone.Collection
url: '/movie/top_movies'
I fetched the collection in console and getting the objects in this manner.
Click to see the Image view of console
I want to display the list on a page. But I am not able to show the list.
movies_router.js.coffee
class Fanboy.Routers.Movies extends Backbone.Router
routes:
"": "index"
initialize: ->
@collection = new Fanboy.Collections.Movies()
@collection.fetch()
index: ->
view = new Fanboy.Views.MoviesIndex(collection: @collection)
$('#movies-container').html(view.render().el)
/view/movies_index.js.coffee
class Fanboy.Views.MoviesIndex extends Backbone.View
template: JST['movies/index']
initialize: ->
@collection.on('reset', @render, this)
render: ->
$(@el).html(@template(movies: @collection))
this
/templates/movies/index.jst.eco
<h4>Top movies of all time </h4>
<ul>
<% for movie in @movies.models : %>
<li><%= movie.get('Title') %></li>
<% end %>
</ul>
Here I am able to see h4 tag but not the list of Titles. What I am doing wrong here? Please someone help.
Update:- I did some debugging. Since the url defined is coming through Omdb API and the view are loaded asynchronously in backbone. Hence the issue.
So I put setTimeout for few seconds and now I am able to display the list. But this makes the app slower. What can I do now?
Though @collection.on('reset', @render, this)
should have handled the issue. But why it is not able to?
Upvotes: 3
Views: 89
Reputation: 2856
Instead of 'reset'
use 'sync'
:
@collection.on('sync', @render, this)
"sync" (model_or_collection, response, options) — when a model or collection has been successfully synced with the server.
Upvotes: 3