我有一个 Ember.js 应用程序,如下(借自 andyMatthews.net 上的 this article):
查看:
<script type="text/x-handlebars" >
{{view App.UserTextField}}
{{#each App.recentUsersArray.reverse tagName="ul"}}
<li>{{this}}</li>
{{/each}}
</script>
应用程序:
App = Ember.Application.create();
App.UserTextField = Ember.TextField.extend({
insertNewline: function(){
var term = this.get('value');
App.recentUsersArray.pushObject(term);
}
});
App.recentUsersArray = Em.ArrayController.create({
content: ['noelle', 'evan', 'mason'],
reverse: function(){
return this.get('content').toArray().reverse();
}.property('content.@each').cacheable(),
});
但我想从 View 将参数传递给 App.recentUsersArray.reverse (例如,设置要返回的反转项目的数量)。我遇到了一个问题,因为虽然您可以接受 Controller 函数上的参数,但似乎无法从 View 中传递它。如果你想将参数 3 传递给 Controller 上的反向函数,我正在想象这样的事情:
{{#each App.recentUsersArray.reverse(3) tagName="ul"}}
<li>{{this}}</li>
{{/each}}
但它抛出一个错误(未捕获错误:解析错误)...想法?最终目标是创建三个 <ul>
的,每个都有不同数量的元素,而无需为每个长度创建不同的函数(即 App.recentUsersArray.reverseThree()
、 App.recentUsersArray.reverseFive()
等)。我也不想制作三个不同的 Controller ,因为每个<ul>
应该使用相同的数据源,只是切片不同。
最佳答案
是的,Ember 可能会被认为是一个奇怪的范例。也许可以尝试:
App.recentUsersArray = Em.ArrayController.create({
recentCount: 3
content: ['noelle', 'evan', 'mason'],
reverse: function(){
var max = this.get('recentCount');
return this.get('content').reverse().slice(0, max)
}.property('content.@each', 'recentCount').cacheable(),
});
//some event handler
App.recentUsersArray.set('recentCount', count)
我不认为 toArray()
是必要的,而且文档说它不能保证返回元素的顺序:
http://docs.emberjs.com/#doc=Ember.Enumerable&method=.toArray&src=false
关于javascript - Ember.js 将参数从 View 传递到 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10653084/