where 筛选器键中的 Backbonejs 变量

Backbonejs variable in a where filter key

本文关键字:Backbonejs 变量 筛选 where      更新时间:2023-09-26

只是想知道是否有人知道为什么我不能在"哪里"中同时获得两个键/值来动态?我可以通过一个完美工作的变量来做这个值,但我似乎根本无法获得运行变量的键。

我的小提琴在这里:http://jsfiddle.net/leapin_leprechaun/eyw6295q/我试图工作的代码如下。

我是骨干网的新手,所以有可能这是你不能做的事情,我只是还不知道!

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

感谢您抽出宝贵时间

您的代码不起作用,因为键"prop"总是按字面意思解释为字符串。因此,您按{"prop": val}而不是按{"location": val}搜索。有几种方法可以解决这个问题

1

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

阿拉伯数字

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

有几种方法可以做到这一点,最简单的方法是创建一个占位符对象,并分配键和值:

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

或者,如果这太冗长,并且开销非常小,则可以使用_.object

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