Will Sheehan
Will Sheehan

Reputation: 25

Input Binding in Ember

I have a form and a live preview of what the form will create.

My model

//campaign.js
export default Model.extend({
  title: attr('string'),
  body: attr('string')
});

In the route

// new.js
export default Ember.Route.extend({
  model () {
    return this.store.createRecord('campaign', {
      title: null,
      body: null
    })
  }
});

My current implementation uses a component for the input

export default Ember.Component.extend({
  keyPress(event) {
    // binding code
  }
});

And in the template

{{#title-input}}
{{/title-input}}
<div id="title-preview"></div>

My Feeling is that there is a cleaner or more idiomatic way to do this. I am new to ember so thank you for any help

Upvotes: 0

Views: 609

Answers (1)

Visualjeff
Visualjeff

Reputation: 111

While the use of Components are compelling they aren't required for capturing form input in ember. For what what its worth. For simple form input the route could be:

setupController() {
    Ember.set('controller','newCampaign', {}); //set empty newCampaign
},

# Action hash would create the new record but only when you have some data.
actions: {
    createCampaign(newCampaign) {
            let newRecord = this.store.createRecord('campaign', newCampaign); //create record
            newRecord.save().then(( /* response */ ) => {
                this.transitionTo('campaigns'); //transition to different page.
            }, (error) => { // Deal with an adapter error
                //handle error
                //rollback if necessary
            });
    }
}

The form or template could be:

{{input name="title" id="title" value=newCampaign.title type="text"}}
{{input name="body" id="body" value=newCampaign.body type="text"}}

Just a suggestion.

Jeff

Upvotes: 1

Related Questions