Reputation: 9808
I've created a view that renders a template with a inputfield. When text gets typed into the inputfield it activates a event that creates a new View and append it to a element that's being renderd in this view.
class Movieseat.Views.Moviesearch extends Backbone.View
template: JST['movieseats/moviesearch']
el: '#moviesearch'
initialize: (opts) ->
{@collection} = opts
@render()
return
render: ->
$(@el).html(@template())
return
events:
"keyup input": "doSearch"
doSearch: (e) ->
@collection.setQuery $(e.currentTarget).val()
@collection.fetch()
view = new Movieseat.Views.Searchresult()
$('#movies').append(view.render().el)
If I'm correct the view and collection are "linked" because of the Moviesearch
name.
But for my Searchresult view I'm using this. And I think I'm not "linking" this to my Moviesearch collection.
class Movieseat.Views.Searchresult extends Backbone.View
template: JST['movieseats/searchresult']
render: ->
$(@el).html(@template(movie: @collection))
this
In the template I render I have this code,
Movie result template
<% for movie in @movie.results : %>
<li><%= movie.original_title %></li>
<% end %>
But when the template gets rendered I get a error.
Uncaught TypeError: Cannot read property 'results' of undefined
(anonymous function)
(anonymous function)
JST.movieseats/searchresult
Movieseat.Views.Searchresult.Searchresult.render
Movieseat.Views.Moviesearch.Moviesearch.doSearch
jQuery.event.dispatch
elemData.handle
Am I correct to think this is a problem with connecting the the searchresult view with the moviesearch collection?
Upvotes: 0
Views: 43
Reputation: 13714
I don't know coffeescript, so I'll write in javascript.
There are a couple of things :
First, Collection fetch is asynchronous by default, so render view only when fetch has completed.
this.collection.fetch().done(function(){
view = new Movieseat.Views.Searchresult()
$('#movies').append(view.render().el)
});
Second, pass the collection to the view
view = new Movieseat.Views.Searchresult({collection:collection});
Third, Save the collection reference
Movieseat.Views.Searchresult = Backbone.view.extend({
initialize:function(opts){
this.collection = opts.collection;
}
});
Upvotes: 1
Reputation: 29073
You need to do @template(@collection)
instead of just @template()
Upvotes: 1