Search code examples
javascriptbackbone.jsampersand.js

Can a Model in Ampersand.js (or Backbone.js) be in multiple Collections simultaneously?


Basically, I want to know if Collections work more like folders (they “physically contain” Models), or playlists (they contain a reference to Models).

If they work like folders, is there a convention for emulating the playlist functionality?


  • FWIW, I’m not modeling playlists — I’m just using them as a metaphor.

  • I found several questions with titles that appeared to be similar to this question. But when I investigated, I couldn’t find a clear answer to my question.


Solution

  • Yes, a model can reside in multiple collections simultaneously.

    function log(msg) { $('body').append('<p>'+JSON.stringify(msg)+'</p>'); }
    
    var m = new Backbone.Model({id: 1});
    var c1 = new Backbone.Collection([m, {id: 2}]);
    var c2 = new Backbone.Collection([m, {id: 3}]);
    
    log(c1.toJSON());
    log(c2.toJSON());
    log(c1.get(1) === c2.get(1));
    log(c1 === m.collection);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://underscorejs.org/underscore-min.js"></script>
    <script src="http://backbonejs.org/backbone-min.js"></script>

    But note that the reference to the collection, m.collection, does not change when you add your model to another collection.