Search code examples
jquerybackbone.jsunderscore.jsunderscore.js-templating

Getting Backbone,JS to load more than one Collection into a single View?


I have a little bit of an issue, I am not sure if I just do not understand it or if what I am trying to do is just not possible. I have a database that loads text, simple plan text on two different pages, home and about.

Now what I am trying to do is load this data / text into a editable div (contenteditable set to true) using Backbone.JS with an Underscore.JS template.

var TextView = Backbone.View.extend({
    el: $(".Loader"), //Template loader placeholder
    render: function() {
        var that = this;
        var AboutTxt = new AboutCollection(); //Get About page text
        var HomeTxt = new HomeCollection(); //Get Home page text
        AboutTxt.fetch({
            success: function(AboutTxt) {
                var BasicTxt = _.template( $('script.BasicText').html(), { AboutTxt: AboutTxt.toJSON() } ); //Load About text into template
                that.$el.html(BasicTxt)
            }
        });
    } //End of render view function
});

So my main question is, can I load more than one Collection into a View, or should / could I load more than one URL into a Collection?

Each of the Collections I have just point to a different URL which gets PHP to return my database data, JSON encoded, into Backbone.

So what is the best method or doing this, or am I completely misunderstanding it?

Thanks

All help very welcome.

UPDATE

These are my Collections

    var HomeCollection = Backbone.Collection.extend({
    url: 'BasicText/home'
});

var AboutCollection = Backbone.Collection.extend({
    url: '/BasicText/about'
});

I don't current have any Models set, but I know this works, If I setup a view to use each of these Collections. My aim is to use just one View to load both of these Collections. So one Collection getting two URL's to get the JSON encoded database data?

Thanks.


Solution

  •     var Model = Backbone.Model.extend({
            urlRoot: './url_to_json',
            initialize: function() {
                            this.about = new collection();
                            this.about.url = urlRoot + '/about';
            }       
    }),
    
        Collection = Backbone.Collection.extend({
            model: Model,
        url: './url_to_json'
        })
    

    Hope this help you