backbone.jsbackbone.js-collections

backbone js getByCid not working


The backbone getByCid is not working when i viewed in console.log it showing the error as TypeError: test.getByCid is not a function. By using at(0).cid it shows the output as 'c1' why its not working.

var test=new Backbone.Collection([ 
   {name:'gowtham',age:10}
]);
console.log(test.at(0).cid); // output as c1
console.log(JSON.stringify(test.getByCid('c1'))); //TypeError: test.getByCid is not a function

Solution

  • the Backbone.Collection does not have method getByCid, thats why you are getting this error.
    But a collection has get method for getting a model.
    it accepts one argument: model | id | cid

    So if you want to get a model by cid, you can do it like this collection.get(cidValue)

    let collection = new Backbone.Collection();
    let test1 = new Backbone.Model({ id: 1, value: 'first' });
    let test2 = new Backbone.Model({ id: 2, value: 'second' });
    
    collection.add([test1, test2]);
    
    console.log(collection.get(2));
    // find test2 by id
    
    console.log(collection.get('c2'));
    // find test2 by cid
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <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.js"></script>