Skip to content

Commit

Permalink
Merge pull request PaulUithol#132 from ClemensSchneider/bug_collectio…
Browse files Browse the repository at this point in the history
…n_add_index

fixed bug where indexes were all the same when adding models to collection
  • Loading branch information
PaulUithol committed Jul 3, 2012
2 parents 7dcd736 + 4dc962e commit f89ee9b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions backbone-relational.js
Original file line number Diff line number Diff line change
Expand Up @@ -1646,6 +1646,16 @@
Backbone.Collection.prototype.trigger = function( eventName ) {
if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' ) {
var dit = this, args = arguments;

if (eventName === 'add') {
args = _.toArray(args);
// the fourth argument in case of a regular add is the option object.
// we need to clone it, as it could be modified while we wait on the eventQueue to be unblocked
if (_.isObject(args[3])) {
args[3] = _.clone(args[3]);
}
}

Backbone.Relational.eventQueue.add( function() {
trigger.apply( dit, args );
});
Expand Down
36 changes: 36 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1622,7 +1622,43 @@ $(document).ready(function() {
Backbone.Collection.prototype.sort = sort;
delete AnimalCollection.prototype.comparator;
});

test( "Raw-models set to a hasMany relation do trigger an add event in the underlying Collection with a correct index", function() {
var zoo = new Zoo();

var indexes = [];

zoo.get("animals").on("add", function(collection, model, options) {
indexes.push(options.index);
});

zoo.set("animals", [
{ id : 1, species : 'Lion' },
{ id : 2, species : 'Zebra'}
]);

equal( indexes[0], 0, "First item has index 0" );
equal( indexes[1], 1, "Second item has index 1" );
});

test( "Models set to a hasMany relation do trigger an add event in the underlying Collection with a correct index", function() {
var zoo = new Zoo();

var indexes = [];

zoo.get("animals").on("add", function(collection, model, options) {
indexes.push(options.index);
});

zoo.set("animals", [
new Animal({ id : 1, species : 'Lion' }),
new Animal({ id : 2, species : 'Zebra'})
]);

equal( indexes[0], 0, "First item has index 0" );
equal( indexes[1], 1, "Second item has index 1" );
});

test( "The 'collectionKey' options is used to create references on generated Collections back to its RelationalModel", function() {
var zoo = new Zoo({
animals: [ 'lion-1', 'zebra-1' ]
Expand Down

0 comments on commit f89ee9b

Please sign in to comment.