Ember.js - binding a button action from a #each loop to its own model

It seems I can’t get the button generated in the template loop #eachto associate the click action with the corresponding model. Here is a brief demonstration of the problem ...

Application Setup Ember.js:

window.Contacts = Ember.Application.create();

Contacts.Person = Ember.Object.extend({
    first: '',
    last: '',
    save: function() {
        // send updated information to server.
    }
});

Contacts.contactsList = Ember.ArrayController.create({
    content:[],
    init: function() {
        this.pushObject( Contacts.Person.create({
            first:'Tom',
            last:'Riddle'
        }));
    }
});

Template:

<script type="text/x-handlebars">
    {{#each Contacts.contactsList}}
    <li>
        {{view Ember.TextField valueBinding="first" viewName="firstname"}}
        {{view Ember.TextField valueBinding="last" viewName="lastname"}}
        <button {{action "save" on="click"}}>Save</button>
    </li>
    {{/each}}
</script>

Problem:

So, the idea in this simple demo scenario is that the “Save” button for each record will trigger an action to save the state of its own model. However, when you click the Save button, an error message appears:

Uncaught TypeError: Cannot call method 'call' of undefined

, "" save . , , . , - , "" undefined. - ? ?

!

+5
2

, - surprise - target, . http://jsfiddle.net/pangratz666/FukKX/:

<script type="text/x-handlebars" >
    {{#each Contacts.contactsList}}
    <li>
        {{view Ember.TextField valueBinding="first" viewName="firstname"}}
        {{view Ember.TextField valueBinding="last" viewName="lastname"}}
        {{#with this as model}}
            <button {{action "save" target="model"}}>Save</button>
        {{/with}}
    </li>
    {{/each}}
</script>

{{#with}} , - this target.


: . , ,...

, , . http://jsfiddle.net/pangratz666/U2TKJ/:

<script type="text/x-handlebars" >
    {{#each Contacts.contactsList}}
    <li>
        {{view Ember.TextField valueBinding="first" viewName="firstname"}}
        {{view Ember.TextField valueBinding="last" viewName="lastname"}}
        <button {{action "save" target="Contacts.contactsController" }}>Save</button>
    </li>
    {{/each}}
</script>

JavaScript

Contacts.contactsController = Ember.Object.create({
    save: function(event) {
        console.log('do something with: ', event.context);
    }
});
+10

:

{{#each answer in effort_reasons itemController="module_answer"}}
{{/each}}

, , - ( ), - Input View, valueBinding . , , Ember , , ,

this.get('controller.parentController')

.

{{action "actionname" parameter paramter2...}}
+2

All Articles