在不使用.get().set()的情况下更新Ember.js中嵌套对象中的值
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);
更新:
经过思考,IMHO这是应该如何完成类似用例的事情的最佳实践,这样您以后就可以使用.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 */];
请参阅此处的完整工作演示。
希望能有所帮助。
相关文章:
- 挖空.js嵌套视图模型不起作用
- ldap.js :嵌套搜索
- Undercore JS嵌套了每个合并对象
- 如何通过node.js嵌套mongodb查询
- d3.js嵌套选择,dos'不起作用
- Angular JS嵌套的ng-repeat只有一个顶级对象
- Angular JS(嵌套变量)中的绑定问题
- 主干.js嵌套模型
- Raphael JS 嵌套转换
- Angular js 嵌套自定义指令
- 需要.js嵌套要求
- Keystone.js嵌套承诺 -> foreach -> 列表查找范围问题
- 聚合物.js嵌套组件中的数据绑定
- Backbone.js嵌套视图中的事件
- Backbone.js嵌套对象结构
- 用继承的数据敲除js嵌套模型
- JS:嵌套函数v原型
- 流星JS -嵌套函数返回值不正确
- 修复对象内多个js嵌套函数的作用域
- Knockout js嵌套控制流绑定不起作用