问题
Template:
{{#each document in documents}}
<div class="col-md-6" {{action "selectDocument" document}}>{{view Ember.Checkbox checked=document.isSelected}} {{document.name}}</div>
{{/each}}
Controller:
App.IndexDocumentsController = Ember.ArrayController.extend({
actions: {
selectDocument: function(document){
document.set('isSelected', !document.get('isSelected'));
}
}
});
When I click on the div, the checkbox toggles 'checked' property. But when I click on the ckeckbox - nothing happens. What can be the reason?
UPDATED Link to jsbin: http://emberjs.jsbin.com/nuvocumuteto/1/edit?html,css,js,output
回答1:
The issue is that when you click on the checkbox 2 things happen.
- the checkbox toggles the
isActive
property, then - the
selectRow
action is ran which again toggles theisActive
property
So the isActive
property ends up staying in the same state that it was.
In your case I would get rid of the action, wrap the checkbox in a <label>
and set the label to display: block
.
The template would look like
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each item in model}}
<li {{bind-attr class="item.isActive:active"}}><label>{{input type="checkbox" checked=item.isActive}}{{item.name}}</label></li>
{{/each}}
</ul>
</script>
and the css would look like
label {
display: block;
}
you would then be able to get rid of the selectRow
action completely because clicking on the label will trigger the checkbox.
You can see a working bin here: http://emberjs.jsbin.com/nuvocumuteto/3/edit
回答2:
I would argue that you are not following "The Ember Way" in two different ways here.
First, Ember.Checkbox
is an internal Ember class (http://emberjs.com/api/classes/Ember.Checkbox.html). The recommended way to render a checkbox is to use the Handlebars input helpers (http://emberjs.com/guides/templates/input-helpers/#toc_checkboxes). This is just wrapping Ember.Checkbox
anyway.
Second, if you want to update the value of isSelected
, the "Ember Way" is to use two-way data bindings. Your code uses one-way data-binding when it reads document.isSelected
and then tries to manually re-create the the data-binding in the other direction when the user clicks by manually writing a selectDocument
action and calling it from an {{action}}
.
Instead, simply bind the Ember Handlebars Input Helper directly to your value like this:
{{#each document in documents}}
<div class="col-md-6">{{input type="checkbox" checked=document.isSelected}} {{document.name}}</div>
{{/each}}
来源:https://stackoverflow.com/questions/25895551/ember-checkbox-nested-in-action-doesnt-change-value