【问题标题】:Backbone and Rails redirect骨干网和 Rails 重定向
【发布时间】:2012-08-03 11:03:40
【问题描述】:

我是主干和 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)

【问题讨论】:

  • 当我返回最后一行的索引视图时,索引视图没有更新为创建的新值。

标签: ruby-on-rails-3.1 backbone.js coffeescript


【解决方案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 方法将新配置文件添加到ProfilesNew 视图中的@collection,然后路由器将其@collection 传递给ProfilesIndex 视图:

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

我认为你应该只有一个集合:路由器中的那个。然后将其交给ProfilesNew 视图:

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

并从ProfilesNew 中删除initialize 方法。视图的initialize 将为您将collection 选项复制到@collection

有几个特殊选项,如果通过,将直接附加到视图:modelcollectionelidclassName、@987654344 @和attributes

强调我的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2014-09-05
    • 1970-01-01
    • 2012-06-09
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多