简体   繁体   中英

Emberjs Checkbox Save to Database

I have a checkbox that needs to save to the database as soon as the value is changed. It is bound to the data element audit. Here is the checkbox in the template:

{{view Site.ReleaseChecklistToggleView checkedBinding="audit" contentBinding="this" placeholder="#"}}

Here is what the Site.ReleaseChecklistToggleView is defined as:

Site.ReleaseChecklistToggleView = Em.Checkbox.extend(
    change: (e)->
        this.content.save()
)

It appears that audit is not being set before change is called. It passes the audit variable as null to the database, but if I do console.log(this.content.audit) in the change method, then it tells me the correct value of true or false . My only conclusion is that it is not updating the ember model until after the change method is being run.

Any advice? Am I using the wrong method?

Try the following:

Site.ReleaseChecklistToggleView = Em.Checkbox.extend(
  valueChanged: ->
    @get("content").save()
.observes("checked"))

Checkout the Ember guide for the Todo application ( http://emberjs.com/guides/getting-started/marking-a-model-as-complete-incomplete/ ). I was able to get auto-saving of a specific attribute working through a checkbox by following this.

In case that link is no longer active, this is how they did it...

Handlebars

<!--- ... additional lines truncated for brevity ... -->
{{#each itemController="todo"}}
  <li {{bind-attr class="isCompleted:completed"}}>
    {{input type="checkbox" checked=isCompleted class="toggle"}}
    <label>{{title}}</label><button class="destroy"></button>
  </li>
{{/each}}
<!--- ... additional lines truncated for brevity ... -->

Controller

Todos.TodoController = Ember.ObjectController.extend({
  isCompleted: function(key, value){
    var model = this.get('model');

    if (value === undefined) {
      // property being used as a getter
      return model.get('isCompleted');
    } else {
      // property being used as a setter
      model.set('isCompleted', value);
      model.save();
      return value;
    }
  }.property('model.isCompleted')
});

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