Backbone 在模板中引用的集合变元

Backbone Collection mutator to reference in template

有没有一种方法可以使用 Backbone.js/Marionette 来使用类似于 Model 中的增变器,但在 Collection 中?例如:

MyCollection.js中:

export default Backbone.Collection.extend({
    model: MyModel,
    ...
    mutators: {
        foo: function() {
            if (this.models.length)
                return this.models[0].get('foo');
            return "default value";
        }
    }
})

然后在MyModel.js:

export default Backbone.Model.extend({
    mutators: {
        foo: function() {
            return "bar";
        }
    }
})

template.ejs中:

<div>
    <h1><%= myCollection.foo %></h1>
    <% for (var myModel of myCollection) { %>
        <span><%= myModel.foo %></span>
    <% } %>
</div>

我似乎收到 TypeError: Cannot read property 'foo' of undefined 错误,所以我想知道这是否可行,或者是否有替代方法?我想避免将 MyCollection.foo 逻辑移动到模板中,但这似乎是最简单的方法。

首先,mutators 不是 backbone 或 marionette 的一部分。看来您正在使用 Backbone.Mutators 插件。它应该与模型而不是集合一起使用。

你的代码有很多问题。首先以下代码无效

foo: {
        if (this.models.length)
            return this.models[0].get('foo');
        return "default value";
    }

其次,您正在尝试从集合和模型的构造函数访问属性。 您应该使用集合实例的 models 属性.

中的数据和访问模型实例创建它们的实例
<div>
  <h1><%= myCollection.foo %></h1>
  <% for (var myModel of myCollection.models) { %>
      <span><%= myModel.get("foo") %></span>
  <% } %>
</div>

我怀疑他们是否使用集合,因为我在文档中没有看到任何关于集合的示例。

请阅读您正在使用的插件和框架的文档,并尝试了解您在做什么...

Backbone.Mutators 插件似乎不支持 Collection。似乎最简单的替代方法是将 Object 添加到 Marionette.ViewserializeData 方法中,即:

serializeData: function() {
    return { models: this.collection.models, foo: this.collection.foo().toJSON() };
}

这里连Mutators都不需要,foo只是MyCollection中的一个函数。

您需要有视图来处理模板和渲染。 Marionette 有一个 CollectionView api,这可能是您正在寻找的, https://marionettejs.com/docs/master/marionette.collectionview.html#rendering-collectionviews 引用文档:

The CollectionView will loop through all of the models in the specified collection, render each of them using a specified childView, then append the results of the child view's el to the collection view's el. By default the CollectionView will maintain a sorted collection's order in the DOM. This behavior can be disabled by specifying {sort: false} on initialize.