【问题标题】:Nesting Marionette regions, layouts and views嵌套 Marionette 区域、布局和视图
【发布时间】:2025-12-16 08:05:02
【问题描述】:

我试图让我的 Marionette 视图与应用程序区域和布局结合使用,但我似乎无法让布局中的嵌套视图呈现。

编辑:我希望OptionsViewBreadcrumbsView 都在NavigationLayout 中呈现,而NavigationLayout 应该呈现在导航区域中。但是,导航区域根本不会呈现。控制台没有显示任何错误。

我的结构如下:

- Navigation region
  - Navigation layout
    - Options region 
    - Breadcrumbs region
- Content region

ItemView 分配给导航区域按预期工作。

App = new Backbone.Marionette.Application();
App.addRegions({
    'nav': '#nav',
    'content': '#content'
});

var NavigationLayout = Backbone.Marionette.Layout.extend({
    template: '#nav-template',
    regions: {
        'breadcrumbs': '#breadcrumbs',
        'options': '#options'
    }
});

var BreadcrumbsView = Backbone.Marionette.ItemView.extend({
    template: '#breadcrumbs-template'
});

var OptionsView = Backbone.Marionette.ItemView.extend({
    template: '#options-template'
});

var ContentView = Backbone.Marionette.ItemView.extend({
    template: '#content-template'
});

App.addInitializer(function(options) {
    var navigationLayout = new NavigationLayout();

    App.nav.show(navigationLayout);
    App.content.show(new ContentView());

    navigationLayout.breadcrumbs.show(new BreadcrumbsView());
    navigationLayout.options.show(new OptionsView());
});

$(function() {
    App.start();
});

可以找到一个简化的测试用例here

【问题讨论】:

  • 没有足够的信息来了解发生了什么。你得到什么错误,如果有的话?您看到的行为与您的预期有何不同?
  • 当然,我的错。更新了问题。
  • 你在使用 Marionette.Async 吗?或此处运行异步的任何其他代码?
  • 不,上面的代码是这个测试用例中的所有Javascript,以及最新版本的jQuery、Underscore、Backbone和Marionette。我更新了整个测试的链接,pastebin.com 似乎已关闭。

标签: backbone.js marionette


【解决方案1】:

好的,终于找到问题了:不能在布局中命名区域options

布局中定义的所有区域都直接附加到布局实例。所以,一个区域定义如下:


Layout.extend({
  regions: {
    options: "#options"
  }
});

最终将layoutInstance.options 设置为Region 实例。这是一个问题,因为 Backbone.View 定义了 options 并将其用于其他目的。

将区域重命名为任何现有视图使用的现有关键字或属性以外​​的任何内容都可以解决此问题。


Layout.extend({
  regions: {
    optionRegion: "#options"
  }
});

在这里工作的 JSFiddle:http://jsfiddle.net/tegon/64ovLf64/

【讨论】:

  • 您的示例如何知道将 HTML 附加到何处?我无法掌握布局如何呈现给 DOM,而无需使用 .html() 或 .append()? *.com/questions/15658403/…
  • @streetlignt 您现在可能已经想通了,但是,您使用的是模板系统。下划线和车把是常用的两种。