backbone js:集合事件函数选项索引未定义

backbone js: collection event function options index undefined

我试图获取模型的索引值。但它返回未定义的值。如何在事件触发后获取索引值。

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});

在您的示例中,我没有看到任何尝试输出模型索引的尝试

Test.on('add',function(model, col, options) {
    console.log('added ' +model.get('name')+'at index '+ `options.index);`
});

也许这只是一个错字。

默认情况下 backbone add 事件回调有这三个参数:modelcollectionoptions 并且没有索引,所以你有自己去拿

我在这里放了一段关于如何获取添加模型的索引的片段 以及如何在特定索引处添加模型

您仍然可以在此处查看更多信息: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>