[英]Updating a value within a nested object within Ember.js without using .get() .set()
我具有以下對象結構,我需要獲取一個特定的標題值,然后將其設置為新值。 我知道一旦進入嵌套對象,就會丟失Ember對象的.get()和.set()方法。 嘗試以標准JavaScript方式設置值導致錯誤,提示必須使用ember.set()。
這是我想在觀察到App.job.code的更改但我斷言失敗時發生的事情:必須使用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"
}
]
}
]
}
]
}
];
我認為以標准的香草方式訪問對象沒有問題: 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')
});
和一些使它生動的夾具:
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 */];
在這里查看完整的工作演示 。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.