Reputation: 12605
Just getting started with backbone, and I thought I was familiar with all the caveats around data binding. Turns out I'm not. If anyone has any ideas as to why the following collection isn't being bound to the IndexView I'd be very appreciative. (Have tried both manually in the browser and in chrome console...untriggered console.log call confirms that render() is not being triggered)
From console, attempted call is:
window.router.project_view.options.projects.create({name: 'TestProject'})
The project is successfully created, but no call to render()
class Backbonescaffolddemo.Routers.CalendarsRouter extends Backbone.Router
routes:
"" : "index"
index: () ->
@projects = new Backbonescaffolddemo.Collections.ProjectsCollection()
...
@project_view = new Backbonescaffolddemo.Views.Projects.IndexView(projects: @projects)
@task_view = new Backbonescaffolddemo.Views.Tasks.IndexView(tasks: @tasks)
...
$('#projects').html(@project_view.render().el)
class Backbonescaffolddemo.Models.Project extends Backbone.RelationalModel
paramRoot: 'project'
class Backbonescaffolddemo.Collections.ProjectsCollection extends Backbone.Collection
model: Backbonescaffolddemo.Models.Project
url: '/projects'
Backbonescaffolddemo.Views.Projects ||= {}
class Backbonescaffolddemo.Views.Projects.IndexView extends Backbone.View
template: JST["backbone/templates/projects/index"]
id: "projects"
initialize: () ->
@options.projects.fetch()
_.bindAll(this, 'addOne', 'addAll', 'render')
@options.projects.bind('reset', @addAll)
@options.projects.bind('save', @addAll)
@options.projects.bind('change', @addAll)
@options.projects.bind('change', @render)
@options.projects.bind('create', @render)
addAll: () ->
@options.projects.each(@addOne)
addOne: (project) ->
view = new Backbonescaffolddemo.Views.Projects.ProjectView({model: project})
$(@el).append(view.render().el)
render: ->
console.log 'render called'
$(@el).html(@template(projects: @options.projects.toJSON()))
return this
Upvotes: 1
Views: 412
Reputation: 77416
Adding a model to a collection, via create
or by any other means, triggers an add
event on that collection, not a create
event. Change
@options.projects.bind('create', @render)
to
@options.projects.bind('add', @render)
Upvotes: 2