2012-08-02 62 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