Skip to content

Commit

Permalink
Added auto-initialization of models with reverse relations.
Browse files Browse the repository at this point in the history
  • Loading branch information
emilisto committed Jan 28, 2012
1 parent f3026f1 commit a27d6b6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
15 changes: 15 additions & 0 deletions backbone-relational.js
Original file line number Diff line number Diff line change
Expand Up @@ -1221,4 +1221,19 @@

return this;
};


// Override .extend() to check for reverseRelations to initialize.
Backbone.RelationalModel.extend = function (protoProps, classProps) {
var child = Backbone.Model.extend.apply(this, arguments);

// Initialize reverse relations
var relations = protoProps.relations || [];
_.each(relations, function(rel) {
if(rel.reverseRelation) new child();
});

return child;
};

})();
25 changes: 25 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,31 @@ $(document).ready(function() {
ok( view.get( 'properties' ).include( props ) );
});

test("Reverse relations are found for models that have not been instantiated", function() {
var View = Backbone.RelationalModel.extend({ });
var Properties = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'view',
relatedModel: View,
reverseRelation: {
type: Backbone.HasMany,
key: 'properties'
}
}
]
});

var view = new View({
id: 1,
properties: [ { id: 1, key: 'width', value: '300px' } ]
});

ok( view.get( 'properties' ) instanceof Backbone.Collection );
});


test("ReverseRelations are applied retroactively", function() {
// Use brand new Model types, so we can be sure we don't have any reverse relations cached from previous tests
var NewUser = Backbone.RelationalModel.extend({});
Expand Down

0 comments on commit a27d6b6

Please sign in to comment.