I tried to get index value for the model. but its returning undefined value. how to get index value once an event is triggered.
var Test=new Backbone.Collection();
Test.add({name:'gowtham',age:20});
Test.add([{name:'eswara',age:25},
{name:'sakthi',age:20}]);
console.log(JSON.stringify(Test));
Test.remove(Test.at(1));
console.log(JSON.stringify(Test));
Test.on('add',function(model, col, options) {
console.log('added ' +model.get('name')+'at index '+ options.index);
});
Test.add({name:'ganesh',age:22});
In your example i do not see any try to output index of a model
Test.on('add',function(model, col, options) {
console.log('added ' +model.get('name')+'at index '+ `options.index);`
});
maybe its just a typo.
By default backbone add
event callback has this three arguments: model
, collection
and options
and there is no index, so you have to get it by yourself
I am putting here snippet about how to get index of added model and how to add model at certain index
you still can check for additional information here: backbonejs.org
let test = new Backbone.Collection([{},{},{}]);
test.on('add', (model, collection) => {
console.log('index is: ', collection.indexOf(model))
});
let model1 = test.add({});
// console: index is: 3
test.add({}, { at:0 });
// console: index is: 0
console.log('model new index: ' + test.indexOf(model1))
// console: model new index: 4
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>