BostonJohn
BostonJohn

Reputation: 2661

scoping of an action helper within a handlebars #each loop

I've become confused about the scoping within an {{#each}} block.

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.

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?

Upvotes: 2

Views: 370

Answers (2)

CraigTeegarden
CraigTeegarden

Reputation: 8251

You can set up an event on ApplicationController and pass in the individual object and call the stored foo(). Inside of the {{#each vars}}...{{/each}} block you can use this to pass the actual object to the event handler.

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

Upvotes: 1

andrew.butkus
andrew.butkus

Reputation: 777

Action in handlebars template not firing

This may be due to the root element, check this posting here for more information

Upvotes: 0

Related Questions