2015-09-25 72 views
0

我想根据获得的值从JSON形成一个集合,Backbone的where看起来像是一个完美的工具,但它看起来像不接受变量。使用Backbone,Lodash或Underscore方法可以实现这种功能吗?将变量传递到Backbone.where

### collection instantiated above 

App.vent.on 'event', (obtained_value) -> 
    desired_models = collection.where(attribute: obtained_value) 
    console.log desired_models 

### outputs empty array 
>[] 

它的工作时,我直接传递key: value,但我需要动态地形成集合。也许我最初采取了错误的路线,解决方案是在另一个方向?

+0

这应该可以正常工作。 'obtain_value'中具体是什么,以及你期望它匹配什么特定的值? 'obtain_value'是一个字符串,但'attribute'的值是一个数字? –

+0

@ muistooshort,这个想法是在另一个视图中基于选择的选项('A')渲染多个模型('B)。 'A'通过'has_many'关系与'B'连接。为了达到这个目的,我的计划是获取所选选项(id)的值,并通过控制器上的Event Aggregator传递它,在那里我可以访问'B'集合。 'B'模型的JSON与'A'模型'a:id'的id相关。因此,通过'A'的编号,我计划将所有相关的B模型作为一个集合检索并传递给它的视图。所以'获得的价值'是数字,'属性是字符串',是的。 –

+0

@ muistooshort我希望那不是太混乱的解释。感谢您的关注。 - curious_gudleif –

回答

0

这不会工作,你需要传递一个对象,因此它会是这样

collection.where({attribute: obtained_value}); 

在coffescript你可以做以下

attribute_var= 
    attribute:obtained_value 

collection.where(attribute_var); 

问候

+0

问题出在CoffeeScript中,它允许使用表示法。 –

+0

好吧,大括号的包装对我来说是这样做的,但@PlatinumAzure指出,我想我可以忽略它们。 –

+0

不幸的是我太匆忙了,没有保存代码。它仍然不起作用。 –

0

我假设你的目标是改变attribute你正在寻找,因为如果价值是多种多样的,对象文字应该工作正常。

你可以做到这一点,而不是对象字面内联。以下是我如何使用JavaScript:

App.vent.on('event', function (obtainedValue) { 
    var finder = {}; 
    finder[attribute] = obtainedValue; 
    desiredModels = collection.where(finder); 
    console.log(desiredModels); 
}); 
+0

,'finder [属性]'返回'属性是undefined'。它只是'desiredModel'的一个属性,难道不应该像我这样无法访问?感谢您的关注。 –