Backbone JS Models and Collections in same file with RequireJS

31st January, 2015 - Posted by david

In BackboneJS, classes/objects are called Models and groups of these models go into Collections. Using RequireJS, you define something and return that something for use in other files. In many BackboneJS examples, I’ve seen say a Person Model and a Person Collection stored in separate files, with each one being imported separately to the script they’re used in. Seeing as you generally use Models and Collections together at the same time, I was looking for a way to have them both in the one file. The solution is pretty simple and involves some simple Javascript object manipulation. I should give credit for this solution to my friend Ronan, although I’m not sure if he came up with it originally!

So, just to illustrate the normal Backbone way of doing things, sticking wih our Person class/object, you might have 2 files in your JS folder, models/person.js and collections/persons.js, as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// models/person.js
define(['underscore', 'backbone'],
  function(_, Backbone) {

    Person = Backbone.Model.extend({
      url: '/person',
      // ... etc
    });

    return Person;
  }
);

//collections/persons.js

define(['underscore', 'backbone', 'models/person']
  function(_, Backbone, Person) {

    Persons = Backbone.Collection.extend({
      model: Person,
      // ... etc
    });

    return Persons;
  }
);

// some other JS file
require('models/person');
require('collections/persons');
var people = new Persons();
people.add(new Person());

So, I’m looking for a way to just have one require‘d file, that will import both my Model and Collection. A way this can be achieved is by defining a Person as a standard Javascript object, then having Model and Collection as attributes of that object. We need to add each attribute one step at a time, we can’t just do it all in one big Person = { // ... } block. Then, once the file is imported, we can do stuff like var people = new Person.Collection();.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// person.js
define(['underscore', 'backbone'],
  function(_, Backbone) {

    var Person = {}; // create initial object

    Person.Model = Backbone.Model.extend({
      url: '/person',
      // ... etc
    });

    // in order to access the Person.Model, we have to specify each attribute separately
    Person.Collection = Backbone.Collection.extend({
      model: Person.Model,
      // ... etc
    });

    return Person;
  }
);

// some other JS file
require('person');
var people = new Person.Collection();
people.add(new Person.Model());

Tags: backbone backbonejs javascript requirejs | david | 31st Jan, 2015 at 9:54am | No Comments

No Comments

Leave a reply

You must be logged in to post a comment.