2013-02-20 80 views
8

我们正在构建基于木偶的应用程序。 基本上,我们有一个在其上定义了多个区域的木偶应用程序。每个区域将充当不同模块的容器以显示其视图。我希望每个模块都能完全控制容器中显示的内容,但我希望应用程序分配这些区域。为了简单起见,假设每个模块只有一个简单的ItemView。木偶 - 应用程序和模块之间的关系

我正在考虑2种方法来使用模块视图填充这些区域。

第一种方法说,当每一模块被初始化时,它会创建视图,它会调用应用程序中所指定的区域,以显示其视图,例如:

var app = new Marionette.Application(); 
app.addRegions({ 
    regionA: "#regionA", 
    regionB: "#regionB" 
}); 

app.module("moduleA", function(moduleA, app, ...){ 
    moduleA.on("start", function(){ 
     var viewA = new MyViewA(); 
     app.regionA.show(viewA); 
    } 
}); 

app.module("moduleB", function(moduleB, app, ...){ 
    moduleB.on("start", function(){ 
     var viewB = new MyViewB(); 
     app.regionB.show(viewB); 
    } 
}); 

第二方法说每个模块应该公开一些返回其视图的函数。应用程序将在准备就绪时调用该函数,并将视图粘贴到指定区域。

我不确定哪种方法更好,并乐于听取意见。

回答

7

我肯定会用第二种方法去,在经历与过去的我现在打这种方法的局限性,并移动到第二个方法的第一种方法之后。我写了一篇关于它的博客文章here

+0

非常真实。模块应该提供一个“容器”视图来渲染模块。它不应该担心如何在DOM中显示它:这是应用程序的工作。保持关注的分离。 – tonyhb 2013-11-08 05:32:45

0

它取决于你采用哪种方法,都很好,我们选择第二个选项,因为我们使用require.js来动态加载模块。

var dashboardPage = Backbone.Marionette.Layout.extend({ 

     template: Handlebars.compile(tmpl), 

     regions: { 
     graphWidget  : "#graphWidget", 
     datePickerWidget: "#datePickerWidget", 
     searchWidget : "#searchWidget" 
     }, 

     widget: { 
      graphWidget: null, 
      datePickerWidget: null, 
      searchWidget: null, 
     }, 

initialize: function(options){ 

     this.someId= options.someId; 

     //if have someId ID - fetch model;   
     if(this.someId){ 
      //fetch model if campaignId not null 
      this.modelAjax = this.model.fetch(); 
     } 

     onShow: function() { 
      var that = this; 

      if(this.modelAjax){ 
      this.modelAjax.done(function(){ 

       that.widget.graphWidget= new graphWidget(graphWidgetOptions); 
       that.listenTo(that.widget.graphWidget, 'graphWidget', that.getGraphWidgetData, that); 
       .... 
       that.graphWidget.show(that.widget.graphWidget); 
       that.datePickerWidget.show(that.widget.datePickerWidget);