Reputation: 23
Trying to learn Aurelia 1.0 and I can't seem to get two-way binding on a custom element to work.
Using bootstrap-datepicker I made a date-range-picker custom element:
date-range-picker.js
import {bindable, bindingMode, inject} from 'aurelia-framework';
import $ from 'jquery';
import datepicker from 'bootstrap-datepicker';
@inject(Element)
export class DateRangePicker {
@bindable startName = 'start';
@bindable endName = 'end';
@bindable startValue = null;
@bindable endValue = null;
constructor(element) {
this.element = element;
}
attached() {
$(this.element).find('.input-daterange').datepicker();
}
}
date-range-picker.html
<template>
<div class="input-daterange input-group" id="datepicker">
<input type="text" class="input-sm form-control"
name="${startName}" id="${startName}"
value.two-way="startValue"
placeholder="Start Date (mm/dd/yyy)" />
<span class="input-group-addon">to</span>
<input type="text" class="input-sm form-control"
name="${endName}" id="${endName}"
value.two-way="endValue"
placeholder="End Date (mm/dd/yyy)"/>
</div>
</template>
the custom element is used in leads.html:
<div class="col-sm-12">
<form role="form" class="form-inline" submit.delegate="search()">
<div class="form-group">
<date-range-picker
start-name="createdAtStartDate" start-value.two-way="startDate"
end-name="createdAtEndDate" end-value.two-way="endDate">
</date-range-picker>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
</div>
leads.js
import {inject} from 'aurelia-framework';
import {LeadsService} from './leads-service';
import moment from 'moment';
@inject(LeadsService)
export class Leads {
startDate = moment().format('M/D/YYYY');
endDate = moment().format('M/D/YYYY');
leads = [];
constructor(dataService) {
this.dataService = dataService;
}
search() {
this.dataService.getLeads({
startDate: this.startDate,
endDate: this.endDate
})
.then(leads => this.leads = leads);
}
}
date-range-picker works as expected and whatever value is set at startDate and endDate in the leads.js is properly bound to the input boxes in the custom element but when I submit the form startDate and endDate doesn't change even if I change the values of the input boxes.
Any ideas what I'm doing wrong?
Upvotes: 2
Views: 1147
Reputation: 11990
The values are being updated by javascript, so you have to dispatch the input's change event, like this:
attached() {
$(this.element).find('.input-daterange').datepicker()
.on('changeDate', e => {
e.target.dispatchEvent(new Event('change'));
});
}
Here's a running example https://gist.run/?id=5d047c561cf5973cf98e88bae12f4b4e
Upvotes: 3