gpt4 book ai didi

properties - 通过关系访问 ember-data 的属性(不在模板中)

转载 作者:行者123 更新时间:2023-12-02 06:11:28 24 4
gpt4 key购买 nike

我想强调这个问题只发生在模板之外,例如当我尝试在 Controller 、单元测试等中访问相关对象的属性时。渲染模板似乎可以很好地获得属性并按预期工作。

这是 JS Bin 中的一个简单示例,测试失败 http://jsbin.com/ihumuk/4/edit这重现了我的问题。通过测试断言该属性可访问并按预期在模板中呈现。失败的测试表明我得到 null当我尝试使用 get 访问该属性时.这里真的没什么好看的,但我不明白为什么它会返回 null .

下面是 JS Bin 示例的应用部分:

App.ApplicationRoute = Em.Route.extend({
model: function() {
return App.Foo.find();
}
});

App.Store = DS.Store.extend({
adapter: DS.FixtureAdapter.create()
});

App.Foo = DS.Model.extend({
name: DS.attr("string"),

/**
* The subject under test
*/
childName: function() {
return this.get("child.name");
}.property("child.name"),

child: DS.belongsTo("App.Bar")
});

App.Bar = DS.Model.extend({
name: DS.attr("string")
});

App.Foo.FIXTURES = [{
id: 1,
name: "Fred",
child: 3
}, {
id: 2,
name: "Barney",
child: 4
}];

App.Bar.FIXTURES = [{
id: 3,
name: "Pebbles"
}, {
id: 4,
name: "Bam Bam"
}];

这通过了。
test("Child name is rendered", function() {
expect(1);

visit("/").then(function() {
ok(find("div:contains(Pebbles)").length);
});
});

这失败了。
test("Child name is accessed", function() {
expect(2);
var foo = App.Foo.find(1);
equal(foo.get("childName"), "Pebbles");
equal(foo.get("child.name"), "Pebbles");
});

这必须是一些简单/愚蠢的事情,比如忘记一个角色或其他东西,但我认为我已经把自己逼得太深了,以至于有一段时间无法清晰地思考。提前感谢您的帮助。

最佳答案

您需要使用 then知道何时加载数据

asyncTest("Child name is accessed", function() {
expect(2);
// load the data from server
App.Foo.find(1).then(function(foo) {
// the child id is 3, we need to fetch the remaining data
// and this is async, because of the ajax request
foo.get("child").then(function(child) {
equal(child.get("name"), "Pebbles");
// childName call child.name, but since the
// data is loaded, isn't necessary to use a second then
equal(foo.get("childName"), "Pebbles");
start();
});
});
});

在 ember 数据中,就像 orm 的专业一样,数据是延迟加载的,用于关系。这是因为,不需要返回所有加载的对象图,让用户询问它想要什么,然后加载。

因为有些实现是异步的,比如:websql、indexeddb、ajax、websockets等。ember-data的接口(interface)是异步的,所以需要使用 then方法来了解数据何时加载或失败。

这些东西在您的模板中起作用,因为它具有绑定(bind)意识。即使更改是异步的,它也会在稍后完成,并且绑定(bind)将被通知和更新。

我更新了你的演示,测试通过了 http://jsbin.com/eqojaj/1/edit

关于properties - 通过关系访问 ember-data 的属性(不在模板中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18222715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com