我有一个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'
}
});
}
);
我喜欢一种只使用继承而不是渲染方法的解决方案,但两者都很好。
答案 0 :(得分: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);
}
});