简体   繁体   中英

backbone.js collections in two levels

So, I'm just started using backbone.js and what I have some troubles understanding how to define two collections where one of them is within a model of the other one.

The REST API looks something like this:

/sites <--- one collection
/sites/123/entities <--- another collection
/sites/123/entities/abc <--- a specific entity within a specific site

This is how the Sites collection is defined:

var ROOT = 'http://localhost:5000';

Site = Backbone.Model.extend({
    defaults: {
        id: "default",
        description: "My site"
    }
});

Sites = Backbone.Collection.extend({
    model: Site,
    url: ROOT + "/sites"
});

How would the Entities collection and model look like to achieve this?

This is how I imagine it would be, though haven't tested it: Entity Model/Collection:

var ROOT = 'http://localhost:5000';
Entity = Backbone.Model.extend({
    defaults: {
        id: "default",
        description: "My Entity"
    }
});
Entities = Backbone.Collection.extend({
    model: Entity,
    ownUrl: '/entities',
    site: {},
    url: function() {
        return (this.site? this.site.url() : '') + this.ownUrl;
    },
    initialize: function(options) {
        this.site = options.site;
    }
});

Site Model/Collection:

Site = Backbone.Model.extend({
    defaults: {
        id: "default",
        description: "My site"
    }
});

Sites = Backbone.Collection.extend({
    model: Site,
    url: ROOT + "/sites",
});

Example of setting up:

// New collection of site
var site1 = new Site({id: 'site1', description: "This is site 1"});
var site2 = new Site({id: 'site2', description: "This is site 2"});
// Add entities to sites
var entityCollection1 = new Entities([
    {id: 'entity1'},
    {id: 'entity2'}
], {site: site1});
// Collection of sites 
var mySites = new Sites([site1,site2]);

Edited:

  • According to Backbone documents, from version 1.1, this.options is not attached automatically anymore. Sorry I was still refer to the 0.9.x code.

In 1.1, Backbone Views no longer have the options argument attached as this.options automatically. Feel free to continue attaching it if you like. http://backbonejs.org/#changelog

  • For the url, my bad, it was supposed to be this.site.url() because it's a model's function which will take the default value as [collection.url/modelId] .

In this case, it should return 'site/1' for Model site1 (ie 'site/2' ) then you append whatever your entity collection url will be.(ex: '/entities' ). This makes your Entities collection url for site 1 become: /site/1/entities . Any model in this collection will have url /site/1/entities/[modelId]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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