javascript - Ember.js 将参数从 View 传递到 Controller 函数

标签 javascript ember.js

我有一个 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/

相关文章:

javascript - 如何通过手机改善网站选项卡之间的交易

javascript - 在 virutemart/Joomla 中通过 rockettheme 在 vm mynxx 模板中使用 AJAX 时出错

javascript - 当存在多个具有相同类的 div 时,如何将内容加载到唯一的 div 中

ember.js - 未捕获的类型错误 : Cannot call method 'connectOutlet' of undefined

javascript - 如何将此 else if 语句转换为 switch 语句?

javascript - ChartJS2 ReactJS 中相同类型的多个图表 - 错误工具提示

javascript - EmberJS : unable to observe @each. 属性.another_property

javascript - 为什么我的 Handlebars #each 循环中的 @first 总是 false?

Ember.js - ember 新命令在主目录而不是当前目录中安装项目

javascript - {{#each}} 内的 Handlebars 助手