Backbone.js [ Rendering a view on a click. / user

2019-08-12 03:45发布

问题:

The server side URL gives me the list of all categories via http://host:3000/categories.json

I'm having category as a model in backbone & I'm catching sub-categories in subCategoriesCollection. At this point of time the URL is http://host:3000/category/1

this would give me a collection of all sub-categories under 1.

what I want is that, to display Each category on a page. That is if there are 10 categories , I need to render view 10 times allowing user to display each category on single page but using same template.

Please guide me about it.

回答1:

This is a typical way to render a collection using a sub view (I'm assuming that's what your refering to when you say "same template").

var SubCategoryView = Backbone.View.extend({
    initialize: function(){
        _(this).bindAll();
    },
    render: function () {
        $(this.el).html(this.model.escape('Name');
        return this;
    }
});
var SubCategoryListView = Backbone.View.extend({
    initialize: function(){
        _(this).bindAll();
    },
    render: function () {
        $(this.el).empty();
        this.collection.each(function (subcategory)
        {
            var childView = new SubCategoryView({
                model: subcategory
            });
            $(this.el).append(childView.render().el);
        });

        return this;
    }
});

Then you can render the category view by passing your sub category collection to the SubCategoryListView

I found this link to be helpful when I was starting out with backbone. It's a little more in-depth but provides a more robust solution that what I just typed in: http://liquidmedia.ca/blog/2011/02/backbone-js-part-3/

Good Luck



标签: backbone.js