Reputation: 7156
I don't understand why the DOM is not updated in the collection view render:
class FastTodo.Views.TodoItemsIndex extends Backbone.View template: JST['todo_items/index'] el: '#main' render: -> $(@el).html @form_view.render() @collection.each @renderOne renderOne: (item) -> console.log(@) console.log(@el) $(@el).append "model data" initialize: -> @collection = new FastTodo.Collections.TodoItems() @form_view = new FastTodo.Views.AddTodoItem collection: @collection @collection.bind 'reset', => @render() @collection.on 'add', (item) => @renderOne(item) @collection.fetch()
The idea is that #main first get a view with add new form, and then the collection is appended to #main.
How would I do this?
The output of the view in the console looks like:
Upvotes: 0
Views: 167
Reputation: 391
1) For @collection.each @renderOne
to work correctly you need to bind your renderOne
method to the view instance like this: renderOne: (item) =>
(notice the fat arrow), because otherwise it is invoked in the global context (that's why you see these Window
objects in your console.
2) DOM element, not the view itself, should be inserted into DOM, so $(@el).html @form_view.render()
should be written as @$el.html @form_view.render().el
(the render
method should return the view instance according to the backbone community convention).
Other looks fine and it should work this way.
You may wish to refer to some posting about context in js to deeper understand the subject (this one for example).
btw you can write less code for some things. i.e. this
@collection.bind 'reset', =>
@render()
@collection.on 'add', (item) =>
@renderOne(item)
can become this
@collection.on 'reset', @render
@collection.on 'add', @renderOne
but you should remember to bind your render
method with the fat arrow in this case.
Upvotes: 1