【发布时间】:2016-03-06 00:14:01
【问题描述】:
我有一个服务,它只是以数组的形式提供数据:
// services/countries.js
import Ember from 'ember';
export default Ember.Service.extend({
countries: [
{
"name": "Afghanistan",
"code": "AF"
},
....
]
});
我可以在助手中成功访问:
// helpers/countries.js
export default Ember.Helper.extend({
countries: Ember.inject.service('countries'),
compute(params, hash) {
console.log(this.get('countries.countries'));
return 'test';
}
});
现在我向该服务添加了一个函数来搜索给定的国家代码并返回匹配的国家:
// in services/countries.js
...
getByCode: function(code) {
this.get('countries').forEach(function(item) {
if(item.code===code) { // finds the right item
console.log('returning item:');
console.log(item); // outputs the right object
return item; // I expected to have the same item retured..
}
});
return {name:'not found', code: ''};
},
...
当我在助手中调用该函数时
// in helpers/countries.js
...
compute(params, hash) {
let country = this.get('countries').getByCode('DE');
console.log(country); // outputs {name: 'not found',..} instead of the found and returned(?) item
return country.name;
}
...
注意,正确的输出(服务中的console.log)在“错误”输出之前:
// console output
returning item: roles.js:6
Object {name: "Germany", code: "DE", nameLocal: "Deutschland"} hash.js:2
Object {name: "not found", code: ""}
让我好奇的是,在控制台中提到了“错误”的 .js(roles.js - 这是另一个服务,没有此功能)
所以我的问题是为什么我会返回/输出不同的项目?
为了完整性: 我只在我的模板中使用过这个助手一次:
{{#if model.country}}{{countries model.country}}{{/if}}
(当然也会输出“错误”的国家)
Ember-CLI 1.13.7 Ember 2.0.1
【问题讨论】:
标签: javascript ember.js