Search code examples
javascriptbackbone.js

Backbonejs variable in a where filter key


Just wondering if anyone knows why I can't get both key/values within a 'where' to be dynamic? I can do the value through a variable, that works perfectly, but I can't seem to get the key to run off a variable at all.

My fiddle is here: http://jsfiddle.net/leapin_leprechaun/eyw6295q/ the code I'm trying to get working is below.

I'm new to backbone so there's a chance this is something you can't do and I just don't know about it yet!

var newCollection = function(myCollection,prop,val){

alert('myprop: ' + prop);
alert('val: ' + val);

var results = myCollection.where({
  //prop: val this doesn't work even if I put a string above it to make sure the value coming through is fine
  //prop: "Glasnevin" //this doesn't work     
  "location" : val //this works

});

var filteredCollection = new Backbone.Collection(results);

var newMatchesModelView = new MatchesModelView({collection: filteredCollection });

$("#allMatches").html(newMatchesModelView.render().el);

}

Thanks for your time


Solution

  • Your code does not work because the key "prop" is always interpreted literally, as a string. So, you search by {"prop": val} not by {"location": val}. There are couple ways how to solve this problem

    1

    var where = {};
    where[prop] = val;
    
    var results = myCollection.where(where);
    

    2

    var results = myCollection.where(_.object([prop], [val]));