【问题标题】:Passing variable into Backbone.where [duplicate]将变量传递到 Backbone.where [重复]
【发布时间】:2015-09-25 17:44:22
【问题描述】:

我想根据获得的值从 JSON 中形成一个集合,Backbone 的 where 似乎是一个完美的工具,但它看起来不接受变量。是否可以使用一些 Backbone、Lodash 或 Underscore 方法来实现这种功能?

### 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 时它确实有效,但我需要动态形成集合。也许我一开始走的是错误的路线,解决方案是另一个方向?

【问题讨论】:

  • 应该可以的。 obtained_value 中的具体内容是什么?您希望它匹配集合中的哪些具体值? obtained_value 是字符串,而 attribute 值是数字吗?
  • @muistooshort,这个想法是渲染多个模型(B), based on the selected option (A) in another view. A`与B通过has_many关系连接。为了实现这一点,我的计划是获取所选选项(id)的值,并通过控制器上的事件聚合器传递它,在那里我可以访问B集合。B模型的JSON与A模型@987654335的id保持关系@.所以ID为A,我计划检索所有相关的B模型作为一个集合并将其传递给它的视图。所以obtained value是数字,attribute is the string,是的。
  • @muistooshort 我希望这不是太混乱的解释。感谢您的关注。 –好奇_gudleif
  • attribute 是变量还是属性?您能否提供collection.where 调用的可运行示例(jsfiddle.net、jsbin.com、sn-p 在您的问题中,...)?你真的在做collection.where(some_numeric_property: some_string_value)吗?
  • @muistooshort 反之亦然:string: id。我创建了this js.fiddle,它无法运行,但我希望它能说明这个过程。非常感谢您的耐心和帮助。

标签: javascript backbone.js underscore.js lodash


【解决方案1】:

我假设您的目标是改变您正在搜索的 attribute,因为如果值不同,对象文字应该可以正常工作。

你可以做到,只是不能使用对象文字内联。下面是我在 JavaScript 中的做法:

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

【讨论】:

  • ,finder[attribute] 返回attribute is undefined。只是desiredModel的一个属性,我这样应该是无法访问的吧?感谢您的关注。
【解决方案2】:

这行不通,你需要传递一个对象,所以它会是这样的

collection.where({attribute: obtained_value});

在咖啡脚本中,您可以执行以下操作

attribute_var=
     attribute:obtained_value

collection.where(attribute_var);

最好的问候

【讨论】:

  • 问题是在 CoffeeScript 中,它允许使用书写的符号。
  • 好吧,用大括号括起来是为我做的,但正如@PlatinumAzure 所说,我想我可以省略它们。
  • 不幸的是我操之过急,没有保存代码。还是不行。
  • 添加了等效的咖啡脚本。它必须工作;)
  • @Sudakatux,不幸的是 id 不起作用。情况相同:当我直接在 attribute: 中传递一个值时,它按预期工作。但是一旦我插入一个变量,它就会返回一个空数组。也许我发送的数据有问题?这只是一个 id。
猜你喜欢
  • 2016-02-22
  • 1970-01-01
  • 2012-06-17
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多