2

我正在准备使用 Backbone Marionette 迁移我的应用程序,但路由中出现错误:

window.App = new Backbone.Marionette.Application
    Models: {}
    Collections: {}
    Views: 
        Layouts: {}
    Routers: {}
    layouts: {}
    Helpers: {}

    init: ->        
        App.start()
        App.main.show(App.layouts.main)

App.addRegions
    main: '#container'

App.addInitializer (options) ->
    new App.Routers.Profiles()
    Backbone.history.start()

$(document).ready ->
     App.init()

这是我的路由器

class App.Routers.Profiles extends Backbone.Marionette.AppRouter
    routes:
            'profiles/:id': 'show'

    show: (id) ->
            @profile = new App.Models.Profile(id: id)
            view = new App.Views.ProfilesShow(model: @profile)
            @profiles = new App.Collections.Profiles(@profile)
            @profile.fetch()
            App.layout.content.show(view)

这是我的观点

class App.Views.ProfilesShow extends Backbone.Marionette.ItemView
    template: JST['profiles/show']

    initialize: ->
        @model.on('change', @render, @)

    render: ->
            $(@el).html(@template(profile: @model))
            @

这是我的主要布局

class App.Views.Layouts.Main extends Backbone.Marionette.Layout
    template: JST['layouts/main']

    regions:
            content: '#content'

App.addInitializer ->
    App.layouts.main = new App.Views.Layouts.Main()

当我尝试在 App.layout.content.show(view) 行中的布局中显示视图时,出现消息错误:“TypeError: App.layout is undefined”。我不知道我是否做得很好。

4

1 回答 1

4

我找到了解决方案。我希望是更好的

主要的变化在路由器,我不得不添加一个控制器,所以新的路由器是

class App.Routers.Profiles extends Backbone.Marionette.AppRouter
    appRoutes:
    'profiles': 'index'
    'profiles/new': 'new'
    'profiles/:id': 'show'

class App.Controllers.Profiles
    constructor: ->
        @collection = new App.Collections.Profiles()
        @collection.fetch()
        App.layouts.main = new App.Views.Layouts.Main()

    show: (id) ->
            profile = @collection.get(id)
            view = new App.Views.ProfilesShow(model: profile)
            App.main.show(App.layouts.main)
            App.layouts.main.content.show(view)

新的 App Init 是:

window.App = new Backbone.Marionette.Application
    Models: {}
    Collections: {}
    Views: 
            Layouts: {}
    Routers: {}
    layouts: {}
    Helpers: {}
    Controllers: {}

    init: ->
            App.start()

App.addInitializer (options) ->
    App.addRegions(main: '#container')
    controller = new App.Controllers.Profiles
    new App.Routers.Profiles(controller: controller)
    Backbone.history.start()

$(document).ready ->
    App.init()
于 2012-08-17T21:54:30.863 回答