2012-08-02 64 views
1

我是新的主干和Rails。当我返回到最后一行的索引视图时,索引视图不会使用创建的新值更新。Backbone and Rails重定向

class App.Views.ProfilesIndex extends Backbone.View 
template: JST['profiles/index'] 

initialize: -> 
    @collection.on('reset', @render, this) 

render: -> 
    $(@el).html(@template(profiles: @collection)) 
    this 

这是我的新视图

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}) 

所以,我需要创建并返回到索引视图的新元素时更新集合代码。

路由器

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) 
+0

当我返回到最后一行的索引视图时,索引视图不会使用创建的新值更新。 – utiq 2012-08-02 17:45:56

+0

我用路由器 – utiq 2012-08-03 00:58:57

回答

1

你有两个不同的App.Collections.Profiles集合。你的路由器有一个:

class App.Routers.Profiles extends Backbone.Router 
    #... 
    initialize: -> 
     @collection = new App.Collections.Profiles() 

而且你ProfilesNew观点有其自身的:

class App.Views.ProfilesNew extends Backbone.View 
    #... 
    initialize: -> 
     @collection = new App.Collections.Profiles() 

createProfile方法添加新的配置文件到@collectionProfilesNew视图,然后路由器手中的@collectionProfilesIndex查看:

index: -> 
    view = new App.Views.ProfilesIndex(collection: @collection) 
    $('#container').html(view.render().el) 

我想你笑uld只有一个集合:路由器中的集合。然后用手即到ProfilesNew视图:

new: -> 
    view = new App.Views.ProfilesNew(collection: @collection) 
    $('#container').html(view.render().el) 

和从ProfilesNew除去initialize方法。视图的initializecollection选项复制到@collection你:

有迹象表明,如果获得通过,将直接连接到视图几个特殊选项:modelcollectionelidclassNametagNameattributes

强调我的。

+0

更新了你的石头!现在一切都好了。 – utiq 2012-08-03 13:06:39