jslamka
jslamka

Reputation: 261

Passing dynamic key-value pairs to function

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!

Upvotes: 2

Views: 6509

Answers (2)

mu is too short
mu is too short

Reputation: 434785

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/

Upvotes: 4

jslamka
jslamka

Reputation: 261

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

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

Upvotes: 0

Related Questions