leapin_leprechaun
leapin_leprechaun

Reputation: 605

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

Upvotes: 0

Views: 41

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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

Upvotes: 2

Nick Tomlin
Nick Tomlin

Reputation: 29241

There are a few ways to do this, the simplest would be to just create a placeholder object, and assign the key and value:

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

Or, if that's too verbose and you are alright with a very small amount of overhead, you could use _.object

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

Upvotes: 2

Related Questions