繁体   English   中英

骨干集合视图渲染

[英]Backbone collection view rendering

我在渲染我的收藏集时遇到问题...当我将其添加到控制台中时,所有这些都能正常工作:

$('body').append(tablesView.render().el);

我从json文件中以li看到了我所有的名字。 之后,我可以使用:

tablesCollection.create({ name:'Next Table Name' });

添加下一个立即渲染的对象。

我的代码:

 window.App = {

    Models: {},
    Views: {},
    Collections: {}
};

window.template = function (id) {

    return _.template($('id' + id).html());
};

// ===========================表格模型

App.Models.Table = Backbone.Model.extend({

    defaults: {
            name: 'Table Name',
        },
});

// ====================== TABLES COLLECTION

App.Collections.Tables = Backbone.Collection.extend({

    model: App.Models.Table,

    url: 'tables.json'
});

// ==============从收集中查看每个表模型

App.Views.Tables = Backbone.View.extend({

    tagName: 'ul',


    initialize: function() {
        this.collection.fetch({reset:true});
        this.collection.on('reset', this.render);
        this.collection.on('add', this.addOne, this );

    },

    render: function () {

        this.collection.each(this.addOne, this);

        return this;

        },

    addOne: function(table) {

        var table = new App.Views.Table({ model: table });

        this.$el.append( table.render().el );

        table.render();

        }

});

// ===========================查看一张桌子的模型

App.Views.Table = Backbone.View.extend({

    tagName: 'li',

    initialize: function() {

      this.model.on('destroy', this.remove, this)  

    },

    render: function () {

        this.$el.html( this.model.get('name') );

        return this;

    },
});

// ===============新收藏实例

var tablesCollection = new App.Collections.Tables();

// =======================新表格视图实例

var tablesView = new App.Views.Tables({ collection: tablesCollection });

非常感谢您的每一个回答! 问候马克罗马特

在尝试呈现集合之前,请确保您正在等待异步获取操作的结果:

tablesCollection.fetch({
    success : function(collection, response, options){
     var tablesView = new App.Views.Tables({ collection: tablesCollection });
     $(document.body).append(tablesView.render().el);
    }
});

尝试这样的事情:

var fetch = mycollection.fetch();
fetch.done(function(){
   $(body).html(_.template(mytemplate, {obj: obj});
});

在初始化集合视图中添加以下内容:

App.Views.Tables = Backbone.View.extend({

    el: '#content',

    template: _.template('<h1>My template</h2>'),

    initialize: function() {
        this.collection = new App.Collections.Tables();
        this.collection.fetch({reset:true});
        this.collection.on('reset', this.render);
        this.collection.on('add', this.addOne, this );

    },
    render: function(){
        this.$el.html(this.template());
    }

....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM