简体   繁体   English

在把手#each循环中确定动作助手的范围

[英]scoping of an action helper within a handlebars #each loop

I've become confused about the scoping within an {{#each}} block. 我对{{#each}}块中的范围界定感到困惑。

If I have the handlebars script 如果我有把手脚本

<script type="text/x-handlebars">
      {{#each vars}}
      <button {{action foo}}> {{name}} </button>
      {{/each}}
</script>

and I set my application controller as 我将应用程序控制器设置为

App.ApplicationController = Ember.Controller.extend({
    vars: Ember.ArrayController.create({
        content: [
            {   name: "Cow",
                foo: function(){console.log("moo");}
            },
            {   name: "Cat",
                foo: function(){console.log("meow");}
            }
        ]
    })
});

The script can see {{name}} just fine and puts it in as the title of the button as you'd expect, but action does not get bound to the foo functions defined within the array members. 脚本可以很好地看到{{name}}并将其作为按钮的标题放入,正如您所期望的那样,但是动作不会绑定到数组成员中定义的foo函数。

Is there are way to do this that I'm missing, or do I need to refactor to make foo be defined directly within ApplicationController ? 有没有办法做到这一点,或者我需要重构以使fooApplicationController直接定义?

You can set up an event on ApplicationController and pass in the individual object and call the stored foo() . 您可以在ApplicationController上设置一个事件,并传递单个对象并调用存储的foo() Inside of the {{#each vars}}...{{/each}} block you can use this to pass the actual object to the event handler. {{#each vars}}...{{/each}}块内部,您可以使用this来将实际对象传递给事件处理程序。

JS: JS:

App.ApplicationController = Ember.Controller.extend({
    vars: Ember.ArrayController.create({
        content: [
            {   name: "Cow",
                foo: function(){console.log("moo");}
            },
            {   name: "Cat",
                foo: function(){console.log("meow");}
            }
        ]
    }),
  doFoo: function(obj) {
    obj.foo();
  }
});

Handlebars: 把手:

{{#each vars}}
      <button {{action doFoo this}}> {{name}} </button>
{{/each}}

JSBin example JSBin示例

Action in handlebars template not firing 车把模板中的动作未触发

This may be due to the root element, check this posting here for more information 这可能是由于root元素所致,请在此处查看此发布以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM