我有以下对象结构,我需要获取特定的标题值,然后将其设置为新值。我知道一旦你进入嵌套对象,就会失去Ember对象.get()和.set()方法。试图设置标准JavaScript方式的值导致错误说必须使用ember.set()。
这是我想要发生的事情,当它观察到对App.job.code的更改但是我的Assertion失败了:你必须使用Ember.set()来访问这个属性([object Object])
updateTitle: function(){
App.jobs.jobProducts[0].allocations[0].allocationTitle = "test2";
}.observes("App.job.code")
如何最好地实现这一目标?感谢
App.jobs = [
{
id: 0,
jobTitle: "This is the only job",
jobProducts: [
{
id: 0,
productTitle: "Product 1",
allocations:[
{
id: 0,
allocationTitle: "Allocation 1",
deliverys:[
{
id: 0,
deliveryTitle: "Delivery 1"
},
{
id: 1,
deliveryTitle: "Delivery 2"
}
]
},
{
id: 1,
allocationTitle: "Allocation 2",
deliverys:[
{
id: 0,
deliveryTitle: "Delivery 3"
},
{
id: 1,
deliveryTitle: "Delivery 4"
}
]
}
]
},
{
id: 1,
productTitle: "Product 2",
allocations:[
{
id: 0,
allocationTitle: "Allocation 3",
deliverys:[
{
id: 0,
deliveryTitle: "Delivery 5"
},
{
id: 1,
deliveryTitle: "Delivery 6"
}
]
},
{
id: 1,
allocationTitle: "Allocation 4",
deliverys:[
{
id: 0,
deliveryTitle: "Delivery 7"
},
{
id: 1,
deliveryTitle: "Delivery 8"
}
]
}
]
}
]
}
];
答案 0 :(得分:0)
我发现以标准香草方式访问对象没有问题:http://jsbin.com/odosoy/74/edit
尝试这样的事情,它是否适合你:
console.log("Title before: "+App.jobs[0].jobProducts[0].allocations[0].deliverys[0].deliveryTitle);
App.jobs[0].jobProducts[0].allocations[0].deliverys[0].deliveryTitle = "FOO";
console.log("Title after: "+App.jobs[0].jobProducts[0].allocations[0].deliverys[0].deliveryTitle);
在考虑之后,恕我直言这是最好的做法,应该像你的用例一样,这样你以后可以使用.set()
,.get()
以及框架给你的所有其他功能:
使用关系定义模型
App.Job = DS.Model.extend({
jobTitle: DS.attr('string'),
jobProducts: DS.hasMany('App.JobProduct')
});
App.JobProduct = DS.Model.extend({
productTitle: DS.attr('string'),
allocations: DS.hasMany('App.Allocation')
});
App.Allocation = DS.Model.extend({
allocationTitle: DS.attr('string'),
deliveries: DS.hasMany('App.Delivery')
});
App.Delivery = DS.Model.extend({
deliveryTitle: DS.attr('string')
});
以及一些将其付诸实践的FIXTURES:
App.Job.FIXTURES = [
{
id: 1,
jobTitle: "This is the only job",
jobProducts: [1,2]
}
];
App.JobProduct.FIXTURES = [
{
id: 1,
productTitle: "Product 1",
allocations:[1,2]
},
{
id: 2,
productTitle: "Product 2",
allocations:[3,4]
}
];
App.Allocation.FIXTURES = [/* shortened */];
App.Delivery.FIXTURES = [/* shortened */];
请在此处查看完整的Demo。
希望它有所帮助。