我想按特定顺序迭代对象属性。我准备了jsbin我的用例示例(使用Ember.js和Handlebars)。我无法找到一种方法来制作
的车把
var months = ['2014-01-01', '2014-02-01', '2014-03-01'];
var datesByMonth = {
'2014-03-01' : [ // march
{ date: '2014-03-10' },
{ date: '2014-03-20' },
{ date: '2014-03-21' }
],
'2014-01-01' : [ // january
{ date: '2014-01-10' },
{ date: '2014-01-20' },
{ date: '2014-01-21' }
],
'2014-02-01' : [ // february
{ date: '2014-02-10' },
{ date: '2014-02-20' },
{ date: '2014-02-21' }
],
};
var monthsCount = months.length;
for(var i = 0; i < monthsCount; ++i) {
var month = months[i];
console.log(month);
var dates = datesByMonth[month];
var datesCount = dates.length;
for(var j = 0; j < datesCount; ++j) {
var obj = dates[j];
console.log(' ', obj.date);
}
}
那么,问题是如何访问存储在其他变量中的键中对象属性的值?
P.S。 版本:EmberJS v1.9.1,Handlebars v2.0.0
P.S.S抱歉我的英文
答案 0 :(得分:1)
我刚刚注意到自v1.10.0以来EmberJS使用HTMLBars作为Handlebars模板编译器。 HTMLBars编译器允许使用帮助器作为子表达式(在Ember v1.9.1&amp; Handlebars v2.0.0中,助手将其结果直接输出到html,而不是父助手),所以我创建了lookup helper类似的把手:
Ember.Handlebars.registerBoundHelper('lookup', function(obj, key) {
return obj && obj[key];
});
帮助程序允许编写这样的模板代码:
<ul>
{{#each month in monthSorting}}
<li>
<h2>{{month}}</h2>
<ul>
{{#each obj in (lookup model month)}}
<li>{{obj.date}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
帮助程序通过使用动态密钥名解决了访问对象内部属性的问题。
答案 1 :(得分:0)
您无法仅使用动态密钥名称访问对象的内部属性。
您可以做的是操纵计算属性months
以返回包含月份键和日期的对象数组。
这是a working JS Bin example
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.Object.create({
'2014-03-01': [ // march
{
date: '2014-03-10'
}, {
date: '2014-03-20'
}, {
date: '2014-03-21'
}
],
'2014-01-01': [ // january
{
date: '2014-01-10'
}, {
date: '2014-01-20'
}, {
date: '2014-01-21'
}
],
'2014-02-01': [ // february
{
date: '2014-02-10'
}, {
date: '2014-02-20'
}, {
date: '2014-02-21'
}
],
});
}
});
App.IndexController = Ember.Controller.extend({
months: function() {
var model = this.get('model'),
months = Ember.keys(model);
return Ember.A(months.map(function(month) {
return Ember.Object.create({
month: month,
dates: model.get(month)
});
}));
}.property('model'),
monthSorting: Ember.computed.sort('months', function(x, y) {
var xTime = new Date(x.get('month')).getTime(),
yTime = new Date(y.get('month')).getTime();
if (xTime > yTime) return 1;
else if (xTime === yTime) return 0;
else return -1;
})
});
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each month in monthSorting}}
<li>
<h2>{{month.month}}</h2>
<ul>
{{#each date in month.dates}}
<li>{{date.date}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
</script>