backbone.relations

The plugin is for defining relations between models.

npm install backbone.relations
2 downloads in the last week
6 downloads in the last month

[npm-badge]: https://badge.fury.io/js/backbone.relations.png

Backbone.Relations

![NPM Version][npm-badge] Build Status Dependency Status

The plugin is for defining relations between models.

Dependencies:

Getting Started

Define models

var User = Backbone.Model.extend({
        initialize: function () {
            this.hasOne(Mailbox, { as: 'mailbox', foreignKey: 'userId' });
        }
    }),

    Mailbox = Backbone.Model.extend({
        initialize: function () {
            this.belongsTo(User, { as: 'user', foreignKey: 'userId' });
            this.hasMany(Message, { as: 'messages', foreignKey: 'mailboxId' });
        }
    }),

    Message = Backbone.Model.extend({
        initialize: function () {
            this.belongsTo(Mailbox, { as: 'mailbox', foreignKey: 'mailboxId' });
        }
    });

Define collections

var UserList = Backbone.Collection.extend({
        model: User
    }),

    MailboxList = Backbone.Collection.extend({
        model: Mailbox
    }),

    MessageList = Backbone.Collection.extend({
        model: Message
    });

Create collections

var userList = new UserList([
        { id: 1, name: 'Dmytro Nemoga' },
        { id: 2, name: 'Andriy Serputko' }
    ]),

    mailboxList = new MailboxList([
        { id: 1, email: 'dnemoga@gmail.com', userId: 1 },
        { id: 2, email: 'aserput@gmail.com', userId: 2 }
    ]),

    messageList = new MessageList([
        { id: 1, text: 'Hi, Dmytro! How are you?', mailboxId: 1 },
        { id: 2, text: 'Hi, Andriy! I\'m fine, thanks!', mailboxId: 2 }
    ]);

Association hasOne

var user = userList.get(1);

user.getMailbox();
user.setMailbox();
user.buildMailbox();
user.createMailbox();

Association hasMany

var mailbox = mailboxList.get(1);

mailbox.getMessages();

Association belongsTo

var message = messageList.get(1);

message.getMailbox();
message.setMailbox();
message.buildMailbox();
message.createMailbox();

Changelog

0.1.7

  • Removed Underscore.String depenedency

0.1.6

  • Removed method toJSON

0.1.5

  • Removed CommonJS support

0.1.4

  • Added CommonJS support

0.1.3

  • Option advanced of toJSON method's renamed to relations

0.1.2

  • Reverted method toJSON

0.1.1

  • Removed method toJSON

0.1.0

  • Initial release
npm loves you