2015-06-24 57 views
2

我有一個Backbone Marionette ItemView,它是父級模板,並具有它自己的模板。 我有一個有不同模板的視圖的孩子。將模板注入到另一個模板

我想將子模板注入父模板的某個位置,以便父代「包裝」子模塊。

define(['backbone', 'marionette', 'jquery', 'hbs!templates/partials/parentContents' ], 
    function(Backbone, Marionette, $, template) { 
    "use strict"; 

     var ParentView = Backbone.Marionette.ItemView.extend({ 
      template: template, 
      /* // contents of parent template 
      <div class="parent"> 
       <div class="parent-head"></div> 
       <div class="parent-body"></div> 
      </div> 
      */ 
      events: { 
       "click .something": "doSomething" 
      }, 
      initialize: function(){ 
       var self = this; 
       // some initialization code 
      } 
     }); 

     // extend events to child class 
     ParentView.extend = function(child) { 
      var view = Backbone.Marionette.ItemView.extend.apply(this, arguments); 
      view.prototype.events = _.extend({}, this.prototype.events, child.events); 
      return view; 
     }; 
    } 
); 

兒童:

define(['jquery', 'hbs!templates/childView', 'backbone', 'views/cards/CardView'], 
    function ($, template, Backbone, ParentView) { 
     "use strict"; 

     return ParentView.extend({ 

      initialize: function(){ 
       var self = this; 
       // do some other stuff 
      }, 

      template: ????, // I want to get the parent's template and inject this template into it at "parent-body" 

      events: { 
       'keypress #something': 'doSomethingElse' 
      } 

     }); 
    } 
); 

我很想只是用繼承,而不是渲染方法的解決方案,但無論是罰款。

回答

2

我不使用木偶,但概念將是相同的。

var ChildView = Backbone.View.extend({ 
    tagName: "div", 
    render: function() { 
     var that = this; 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 


var MasterView = Backbone.View.extend({ 
    el: "#master-element", 
    render: function() { 
     var $el = this.$el.find("#child-holder"); 
     var view = new ChildView({model: something}); 
     $el.html(view.render().$el); 
    } 
}); 

下面是如何我通常接近與繼承的觀點:

var RootView = Backbone.View.extend({ 
    template: function(data){ 
     return JST[this.templateName](data); 
    }, 
    tagName: "div", 
    render: function() { 
     var that = this; 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 


var ChildView = RootView.extend({ 
    templateName: "child-view", 
    tagName: "div" 
}); 


var MasterView = RootView.extend({ 
    el: "#master-element", 
    templateName: "master-view", 
    render: function() { 
     RootView.prototype.render.apply(this, arguments); 
     var $el = this.$el.find("#child-holder"); 
     var view = new ChildView({model: something}); 
     $el.html(view.render().$el); 
    } 
}); 
+0

謝謝,我把這個概念和使用的渲染方法,你車把一起提出注入標記爲母體,然後使其正確。不是我想要這樣做的方式,但效果很好。 (我正在尋找一種解決方案,涉及到繼承來抓取模板和做東西給他們) – SoluableNonagon

+0

我更新了我的答案,向您展示了一種使用視圖繼承的方法。在示例中,我使用預編譯的車把視圖。 – tribe84