I’m new with backbone and Rails. When I return to the index view in the last line, the index view is not updated with the new value created.
class App.Views.ProfilesIndex extends Backbone.View
template: JST['profiles/index']
initialize: ->
@collection.on('reset', @render, this)
render: ->
$(@el).html(@template(profiles: @collection))
this
And this is my code for the new view
class App.Views.ProfilesNew extends Backbone.View
template: JST['profiles/new']
initialize: ->
@collection = new App.Collections.Profiles()
events: ->
'submit #new_profile': 'createProfile'
render: ->
$(@el).html(@template())
this
createProfile: (event) ->
event.preventDefault()
attributes = name: $('#new_profile_name').val()
@collection.create attributes,
success: -> Backbone.history.navigate("/profiles", {trigger: true})
So, I need to update the collection when the new element is created and returned to index view.
Router
class App.Routers.Profiles extends Backbone.Router
routes:
'profiles': 'index'
'profiles/new': 'new'
initialize: ->
@collection = new App.Collections.Profiles()
@collection.fetch()
index: ->
view = new App.Views.ProfilesIndex(collection: @collection)
$('#container').html(view.render().el)
new: ->
view = new App.Views.ProfilesNew()
$('#container').html(view.render().el)
You have two distinct
App.Collections.Profilescollections. Your router has one:And your
ProfilesNewview has its own:Your
createProfilemethod adds the new profile to the@collectionin theProfilesNewview and then the router hands its@collectionto theProfilesIndexview:I think you should have just one collection: the one in the router. Then hand that to the
ProfilesNewview:and remove the
initializemethod fromProfilesNew. A view’sinitializewill copy thecollectionoption to@collectionfor you:Emphasis mine.