(Note that as with many jQuery plugins in JSPM you have to use jspm install npm:jquery-datetimepicker -o "{format: 'global'}")

Adding it to Aurelia proved a little tricky though. First I thought I’d quickly ‘bodge’ it in to check the functionality, so I added some code to the attached() method of my view to call the jquery extension it had added:

XHTML

1

2

3

4

5

6

<input

value.bind="options.deactivateDate"

placeholder="Deactivate at..."

type="datetime"

ref="dt_activate"

/>

JavaScript

1

$(this.dt_activate).datetimepicker();

But things didn’t quite go as expected. While the popup appeared, and the value changed, it wasn’t being bound to the underlying deactivateDate in my object.

Well, it turns out that this is an issue in that jQuery doesn’t always fire change and input events when modifying values in input fields, so the easiest way to solve this is simply to call the event yourself.

So, I might as well bundle this whole thing into a custom attribute, saving the hassle of adding anything in attached() as this will be resolved automatically at the appropriate time:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import{inject,customAttribute}from'aurelia-framework';

@customAttribute('datepicker')

@inject(Element)

exportclassDatePicker{

constructor(privateelement){

}

attached(){

($(this.element)asany).datetimepicker()

.on('change',e=>fireEvent(e.target,'input'));

}

detached(){

// remove it in here if possible!

}

}

functionfireEvent(element,name){

varevent=document.createEvent('Event');

event.initEvent(name,true,true);

element.dispatchEvent(event);

}

I save this as datepicker.tsand add it to the list of global resources (so I don’t have to bother using <require> to import it), and my final front-end code looks like this:

XHTML

1

2

3

4

5

6

<input

value.bind="options.deactivateDate"

placeholder="Deactivate at..."

type="datetime"

datepicker

/>

The only other thing to do is to tidy the display up a bit, so it’s not displaying the date and time in full UTC format.

Simply done using a ValueConverter (using moment imported from NPM):

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

import*asmoment from'moment'

exportclassDateFormatValueConverter{

toView(value){

console.warn('to',value);

returnmoment(value).format('YYYY-MM-DD HH:mm');

}

fromView(value){

console.warn('from',value);

returnmoment(value,'YYYY-MM-DD HH:mm');

}

}

Bear in mind that this is being displayed in current time, not UTC, so you may choose to modify the converter to display locally but read and write as UTC to the underlying object.

jasonsays:

Yes, I tried that control first, then switched, but the same process applies to both.
The code to make them global in aurelia is simply config.globalResources.
I’ll stick it in a blog post to make it more readable.