I have an Ember model with a date attribute to store a user's birthday. I would like to bind the value of this attribute to three html select tags (one for month, day, and year), but I don't know how. Since the data is stored on the model as a timestamp, it's not as simple as binding an html element straight to a model property.
I'm using ember 1.12 and ember-cli. I've looked into emberx-select for constructing and binding to the actual select and option elements, but I'm not sure how to bind each select to a distinct piece of the date attribute.
Thanks for your help.
You cant directly connect to the model using the DS.attr(date)
,but You can create a js date from three inputs, and then assign the date to the models attribute
Since ember is going the path of data down actions up, in my example i built a component that fires a dateChanged event everytime the inputs are updated with a valid date
http://emberjs.jsbin.com/vuyoso/edit?html,js,output
App.IndexController = Ember.Controller.extend({
date:new Date(2001,2,2),
actions:{
dateChanged:function(date){
this.set('date',date);
}
}
});
App.DateInputComponent = Ember.Component.extend({
day:null,
month:null,
year:null,
onDateChanged:function(){
var date = new Date(this.get('year'), this.get('month'), this.get('day'));
if(date !== 'Invalid Date'){
this.sendAction('dateChanged',date);
}
}.observes('day','month','year')
});
<script type="text/x-handlebars" id="components/date-input">
day:{{input value=day}}<\ br>
month:{{input value=month}}<\ br>
year:{{input value=year}}<\ br>
</script>
<script type="text/x-handlebars" data-template-name="index">
{{date-input dateChanged="dateChanged"}}
{{date}}
</script>
To go from date to day,month,year
Use ember computed to transform the date object
Model :
export default DS.Model.extend({
date:DS.attr('date'),
year:Ember.computed('date',function(){return this.get('date').getYear()}
month:Ember.computed('date',function(){return this.get('date').getMonth()}
day:Ember.computed('date',function(){return this.get('date').getDay()}
})
Or Component:
{{my-component date=date}}
export default Ember.Component.extend({
year:Ember.computed('date',function(){return this.get('date').getYear()}
month:Ember.computed('date',function(){return this.get('date').getMonth()}
day:Ember.computed('date',function(){return this.get('date').getDay()}
})