2

I am probably overlooking something or just being a noob but, I am having trouble being able to pass key-value pairs to a javascript function.

I am writing a filter module utilizing a Backbone.View and Backbone.Paginator.clientPager collection. I added a function to the clientPager called whereExpanded() which searches the entire collection without modifying/rendering anything.

Backbone.Paginator.clientPager.prototype.whereExpanded = function(attrs) {
  return _.filter(this.origModels, function(model) {
    var key;
    for (key in attrs) {
      if (attrs[key] !== model.get(key)) {
        return false;
      }
  });
};

As you can see, it takes the attrs variable and loops over it. I want to be able to pass in key value pairs to this but, the key and value need to be dynamic.

collection.whereExpanded(filterByField, filterByValue)

filterByField is the attribute of the Backbone.Model I wish to filter by and filterByValue is the value of the attribute I want to filter. I have tried utilizing eval() but I cannot seem to get that to work either.

Any help woudl be greatly appreciated!

jslamka
  • 261
  • 2
  • 5
  • 14

2 Answers2

4

You don't need eval for this, you can build an object in better ways:

var attrs = { };
attrs[filterByField] = filterByValue;

And with a small bit of effort, you can let your function be called in various different ways:

whereExpanded({ k1: v1, k2: v2 });
whereExpanded('k1', v1);
whereExpanded('k1', v1, 'k2', v2);

You just need to parse arguments yourself with something like this:

argv  = [].slice.call(arguments);
attrs = {};
if(argv.length == 1 && _(argv[0]).isObject()) {
    attrs = argv[0];
}
else if(argv.length % 2 == 0) {
    for(var i = 0; i < argv.length; i += 2) {
        attrs[argv[i]] = argv[i + 1];
    }
}
else {
    throw 'Bad argument list';
}

That will leave you with the key/value pairs in attrs that your _.filter is expecting.

Argument parsing demo: http://jsfiddle.net/ambiguous/e5kkc/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    This is the right answer. There are [good reasons not to use eval](http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea). – voithos Aug 24 '12 at 17:49
  • eval is dangerous, and is a target for XSS attacks. There are very narrow circumstance where you can use eval, but they are so few that it doesn't make any sense to use it. Better to use arguments as explained above. – Brendan Delumpa Aug 24 '12 at 18:59
0

It looks like eval() did work in the end. I was being a noob.

eval("collection.whereExpanded({" + filterByField + ": " + filterByValue + "})")

jslamka
  • 261
  • 2
  • 5
  • 14