javascriptbackbone.jsbackbone.js-collections

How to get elements from object where in Backbone?


I have object-model as:

var wo = new WordModel({
    "url": window.location.href,
    "time": toDay(),
    "w": w.trim()
});

timelineCollection.add(wo);

I try to get all element in timelineCollection where time is 04/02/2017. I tried this:

var o = {
    time: "04/02/2017"
};

var filtered = timelineCollection.where(o);
console.log(filtered);

But it does not work for me


Solution

  • Backbone's collection where function is really what you should use for this.

    // short syntax, every object becomes a Backbone.Model by default.
    var collection = new Backbone.Collection([{
        id: 0,
        time: "04/02/2017",
      }, {
        id: 1,
        time: "05/02/2017",
      },
      // you can mix both plain objects and Model instances
      new Backbone.Model({
        id: 2,
        time: "04/07/2017",
      }), new Backbone.Model({
        id: 3,
        time: "04/02/2017",
      })
    ]);
    
    // passing an existing model works too.
    var model = new Backbone.Model({
      id: 4,
      time: "04/02/2017",
    });
    
    collection.add(model);
    
    console.log(collection.where({
      time: "04/02/2017"
    }));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>