Skip to content

Commit

Permalink
Allow related models to be set in the key attribute even when keySour…
Browse files Browse the repository at this point in the history
…ce is

defined. See #187
  • Loading branch information
tom-pryor committed Nov 3, 2012
1 parent 4fcbb19 commit ed68e39
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
19 changes: 12 additions & 7 deletions backbone-relational.js
Expand Up @@ -411,15 +411,20 @@
}

if ( instance ) {
this.keyContents = this.instance.get( this.keySource );
var contentKey = this.keySource;
if ( contentKey !== this.key && typeof this.instance.get( this.key ) === 'object' ) {
contentKey = this.key;
}

// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
if ( this.key !== this.keySource ) {
this.instance.unset( this.keySource, { silent: true } );
}
this.keyContents = this.instance.get( contentKey );

// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
if ( this.keySource !== this.key ) {
this.instance.unset( this.keySource, { silent: true } );
}

// Add this Relation to instance._relations
this.instance._relations.push( this );
// Add this Relation to instance._relations
this.instance._relations.push( this );
}

// Add the reverse relation on 'relatedModel' to the store's reverseRelations
Expand Down
32 changes: 32 additions & 0 deletions test/tests.js
Expand Up @@ -1381,6 +1381,38 @@ $(document).ready(function() {
equal( companyA.get('employees').length, 2, 'with elements' );
});

test("If keySource is used don't remove a model that is present in the key attribute", function() {
var ForumPost = Backbone.RelationalModel.extend({
// Normally would set something here, not needed for test
});
var ForumPostCollection = Backbone.Collection.extend({
model: ForumPost
});
var Forum = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'posts',
relatedModel: ForumPost,
collectionType: ForumPostCollection,
reverseRelation: {
key: 'forum',
keySource: 'forum_id'
}
}]
});
var TestPost = new ForumPost({
id: 1,
title: "Hello World",
forum: {id: 1, title: "Cupcakes"}
});

var TestForum = Forum.findOrCreate(1);

notEqual( TestPost.get('forum'), null, "The post's forum is not null" );
equal( TestPost.get('forum').get('title'), "Cupcakes", "The post's forum title is Cupcakes" );
equal( TestForum.get('title'), "Cupcakes", "A forum of id 1 has the title cupcakes" );
});


module( "Backbone.HasOne", { setup: initObjects } );

Expand Down

0 comments on commit ed68e39

Please sign in to comment.