Backbone Marionette 项目视图 return html

Backbone Marionette ItemView return html

我想呈现 marionette ItemView 并将结果 html() 附加到我的 div。 我的代码:

 var ProjectItemView = Backbone.Marionette.ItemView.extend({
        template: "#ProjectItem",
        tagName: 'div',
    initialize: function () {
        this.model.on('change', this.life, this);
        this.model.on('change', this.render, this);
    },

    life: function () {
        alert(JSON.stringify(this.model));
    }
});


var tmp = new Project({project_id: 1});
tmp.fetch();

$('#container').append(new ProjectItemView({model: tmp}).$el);

life: function 中的警报显示模型正确。这意味着 fetch 工作正常。
问题是 - 如何获得 html 作为视图的结果。
我也试过 $('#container').append(new ProjectItemView({model: tmp}).render().el);

问题出在我用来填充 collections/models 的 REST 服务上。它 returns 包含一个元素的数组 - 不是直接的普通对象。

您必须对来自 marionette 的 render 事件作出反应。

...
onRender : function() {
  $('#container').append(this.$el);
}
...
new ProjectItemView({model: tmp});
tmp.fetch();

如果您想解耦,请从您的视图处理程序中向外界触发一个不同的应用程序事件。 Radio 如果您还没有,可能值得考虑。

我认为你的问题只是操作的顺序。试试这个:

$('#container').append((new ProjectItemView({model: tmp})).render().el);

您之前的方式是在构造函数上调用 .render()。使用上面的额外括号,.render() 在实例上被调用。

将元素传递给视图:

new ProjectItemView({model: tmp, el:'#container'}).render();