背景
我正在编写一些功能测试来测试我的路由器是否正确导航和加载我的模型。到目前为止,一切都很好——即使考虑到这个问题。
我创建了a fiddle ,供您欣赏。它不起作用——尽管有 fork @wagenet,但我在 jsfiddle 和 ember 方面从来没有什么运气。 。但它有更多的源代码来帮助我全面了解我正在发生的事情。
我最大的提示
所以我最大的提示是以下代码无法从 Controller 检索具有已知 id 的元素:
var controller = App.__container__.lookup("controller:postsNew");
var type1Option = controller.get("controllers.types").findBy("TYPE1");
我在 setupController Hook 中做了类似的事情并且它有效。但这是在我的应用程序的上下文中,所以它看起来更像是这样的:
setupController: function(controller, model) {
this._super(controller, model);
this.controllerFor("types").findBy("TYPE1");
}
但即使这样也不再起作用了!我现在也在我的应用程序之外工作——进行 qunit 测试。因此,根据我读过的所有内容,我必须使用 App.__container__.lookup()
。
根?
我发现 controller.length
未定义 - 这导致 .findBy()
失败。并且这些项目存在于数组中......至少,我可以通过执行 controller.toArray()
来看到它们。
临时解决方案
以下是我必须做的:
var controller = App.__container__.lookup("controller:postsNew");
var type1Option = null;
$.each(controller.get("controllers.types").toArray(), function(index, elm) {
if (elm.get("id") === "TYPE1") {
type1Option = elm;
return true;
}
});
这显然不那么干净。
那么,问题
.findBy()
损坏了吗?- 我做的
.findBy()
错了吗? - 如何使用
.findBy()
?
最佳答案
findBy
采用 2 个参数,即要测试的属性键和要查找的值(如果未传入,则默认为 true)。本质上,您正在搜索属性 TYPE1
为 true
您可能想这样做
findBy("id", "TYPE1")
http://emberjs.com/api/classes/Ember.Array.html#method_findBy
Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to true.
关于ember.js - 将 .findBy() 与 Ember 数据填充的数组 Controller 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804650/