简体   繁体   中英

Ember.js action on checkbox with dynamic generated id

In an Ember.js 2.11 template I have an each cycle that iterate on a model. Inside it I place an input checkbox whit dynamic generated id (like "chk-"+row_model.id). This checkbox isn't associated with any model option but enable/disable (maybe with a css class) only another input text with the same style dynamic generated id (like "txt-"+row_model.id).

How can I do this?

template:

{{#each model as |row|}}
    <div>
       <input type="checkbox" id="chk-{{row.id}}" 
            onchange={{action (action "checkboxChanged" row.id) value="target.checked"}}> 
     <input disabled type="text" id="txt-{{row.id}}">
  </div>
{{/each}}

controller/component:

  actions: {
    checkboxChanged(rowId, isChecked) {
      Ember.$('#txt-' + rowId).prop('disabled', !isChecked);
    }
  }

Ember Twiddle

You could use some artificial attribute (like _checked ) in the model as well. Or, better yet, write a component. So previous example could be rewritten using components like this:

checked-input.hbs:

<input type="checkbox" onchange={{action (mut isChecked) value="target.checked"}}> 
<input disabled={{isDisabled}} type="text">

checked-input.js:

import Ember from 'ember';

export default Ember.Component.extend({
  isDisabled: Ember.computed.not("isChecked")
});

using it:

{{#each model as |row| }}
   {{checked-input row=row}}
{{/each}}

Ember Twiddle

Basically, avoid direct manipulation of DOM if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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