javascript - Backbone.js 在 View 中渲染集合

标签 javascript backbone.js underscore.js

我有一个主干集合,我正在尝试在 View 中渲染它。 JSON 数据似乎是正确的,但我无法从 View 中访问这些值。

这是基本集合:

define(['backbone', 'BaseModel'], function(Backbone, BaseModel) {

    var BaseCollection = Backbone.Collection.extend({

         model: BaseModel,
         url: "/collection/get?json=true",

         initialize: function() {}
    });

    return BaseCollection;

});

这是 View :

define(['backbone', 'BaseCollection'], function(Backbone, BaseCollection) {

    var BaseView = Backbone.View.extend({

        el: $('#baseContainer'),
        template: _.template($('#baseTemplate').html()),

        initialize: function() {
            _.bindAll(this);
            this.collection = new BaseCollection();
            this.collection.bind('all', this.render, this);
            this.collection.fetch();
        },
        render: function() {   

            //This returns 3 objects which is correct based on the JSON data being returned from the server
            console.log(this.collection.toJSON());

            var html = this.template(this.collection.toJSON());
            this.$el.html(html);
            return this;
        },

    });

    return BaseView;

});

我认为我需要为集合中的每个模型迭代 this.render 。但是,我不确定,因为在完成所有迭代之前它不应该“渲染”。

任何建议都会很棒!谢谢!

最佳答案

您需要让模板通过名称访问模型。当你这样做时:

var html = this.template(this.collection.toJSON());

您最终将一个数组传递给 template 函数,该函数通常需要一个上下文对象(名称/值对)。试试这个:

var html = this.template({collection: this.collection});

然后在模板中,您可以使用collection.each迭代器函数或任何用于迭代/过滤/映射/等的下划线实用方法来迭代它们。我还建议在为您的模板提供对集合的访问权限时不要使用 toJSON,因为它会使您的数据变得更加愚蠢且难以使用。 toJSON 最好在发出 HTTP 请求时使用。

关于javascript - Backbone.js 在 View 中渲染集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233095/

相关文章:

javascript - 如何使用 jquery 获取 Mvc Telerik Grid 中的行值

javascript - Android WebView 下载然后稍后显示在 AlertDialog 中

javascript - Backbone : Listening for button clicks on seperate view

javascript - 如何从 fetch 返回 ajax 结果

javascript - 通过属性查找一个数组中不存在于另一个数组中的对象

javascript - 在 catch block 内调用抛出函数是否安全?

javascript - 由于缓存,我的网页未加载更改

javascript - 主干中(view.$el 和 $(view.el))之间的差异

javascript - 没有唯一键的 lodash indexBy

Node.js 和 Underscore.js