Search code examples
ember.jsember-data

Ember Data: Change model data in component and write it back to API


I'm learning ember.js right now and having trouble to understand how editing model data works. I have a simple model called singleitem:

export default Model.extend({
    test: DS.attr('string')
});

There's a template singleitem.hbs that uses a template component interface_text.hbs containing this line:

<input type="text" value="{{singleitem.test}}" />

And a corresponding interface_text.js component:

export default Component.extend({
    change() {
        console.log(this);
    }
});

Whenever I change the content of the <input> tag, the change() method fires, so this works. But how do I update the model with the new value of the <input>?

(My ultimate goal is to write the changed data back to my API. Using this.test.save(); initiates a PATCH request to my API, but sends back the unaltered data. So I think I have to change the model first.)


Solution

  • The easiest way to use two-way binding for inputs is to use the input helper provided by ember

    To simplify the examples, imagine you are using a component with a property called test:

    // template.hbs
    {{input value=this.test}}
    

    The second easiest way is to use the mut helper with an HTML input tag:

    // template.hbs
    <input type="text" value="{{this.test}}" oninput={{action (mut this.test) value="target.value"}}/>
    

    Instead of using the mut helper, you can assign an action to that event:

    // template.hbs
    <input type="text" value="{{this.test}}" oninput={{action "changed"}}/>
    
    // component.js
    actions: {
      changed(e) {
        this.set('test', e.target.value);
      }
    }
    

    In any case, there are some important concepts you need to learn to be able to reach your goal, so I strongly recommend you to read the Ember documentation. There's a great tutorial that covers all you need to start working with Ember.