I’m new to Backbone + new to CoffeeScript. I have a collection which retrieves data (properties) from a URL. In my homeView I append this data to a template and loop through it:
<ul>
<% _.each(data, function (row) { %>
<li><%= row.get('name') %></li>
<% }); %>
</ul>
This works fine.
However, when I want to view an individual row (property), I still use the same collection and change an attribute in my model (id), to change the URL being called in the collection & retrieve only one piece of data (one property).
The way I have coded it is, in my individual property view, it still loops through the collection (even though there’s only on row), and appends it to the main view
class ShowPropertyView extends Backbone.View
constructor: ->
super
initialize: ->
@Property = new PropertyCollection #New collection
@Property.PropertiesModel.set({theID: @options.theID}) #Change URL and get one property with a specific ID
template: _.template($('#showProperty').html())
#propertyInfoTemplate: _.template($('#propertyInfoTemplate').html())
render: ->
#$(@.el).html(@template) #load main template
@loadResults() #load individual property
loadResults: ->
@Property.fetch({
success: (data) =>
$('#propertyInfo').append(@propertyInfoTemplate({data: data.models, _:_})) #Load data into another template & append template to main template
error: ->
alert('Unable to load information')
})
And the current template (which receives the data & gets appended to the main template) looks like this (which is similar to my homeView template):
<div>
<% _.each(data, function (row) { %>
<div>
<h3><%= row.get('name') %></h3>
</div>
<% }); %>
</div>
Want I need to achieve is the ability to pass the information into the one single view, and remove the need for the looping statement in underscore and not have to append this to the main view (as it’s just only an individual piece of data).
so I just have one single view that just looks like this:
<div>
<h3><%= row.get('name') %></h3>
</div>
I no I need to change something in ShowPropertyView, I’m just not sure what?
Any help would be much appreciated! Thanks.
I think that the best idea to solve your problem is to split described functionality into two views. I really recommend to use backbone.js convention to implement simple views by passing to their constructors model instance or collection instance, like in docs.
The code for this solution is shown below. Firstly view for one model
And template for that:
Code for collection view:
And template for collection handling:
Code above you can use it like that, for example in your router:
and for collection
Sometimes when collection view is a bit complicated, for example with some actions for every row, it is good to implement a nested view (that represents row). This approach is simpler and more legibility, because for every row you can use events mapping.