When working with Knockout you use the HTML5 attribute data-bind. Take the following code for example that puts a user’s name in the
This code basically places “Sample User” inside of the span tag. Now let’s say that you would like to put a “date” in there. Maybe your ViewModel included a Date of Birth.
With Knockout, the dateString binding does not exist. However, like any great framework, you can extend behavior. What we need to do is create a Custom Binding. The following code will create our DateString formatter and it leverages the Moment.js library for date formatting. Check it out if you haven’t at this point.
Just a quick basic, from the knockout documentation, “update” will be called once when the binding is first applied to an element, and again whenever the associated observable changes value. Update the DOM element based on the supplied values here. Now that’s out of the way, let’s get to the meat of our function.
The function takes the value of the object as well as any binding options. The value is unwrapped via the ko.utils function which returns the actual object value. The datePattern is fished out of the allBindingsAccessor to build the format that we would like to apply. You can of course customize the “default” behavior here in this method leaving datePattern unneeded in many occasions. Lastly, if the value is defined, I build a date from Moment in the ISO 8601 format and then output the date in the format represented in datePattern.
Pull all of this together, and you get nice and clean date formatting leveraging what Knockout gives you plus adding a little something extra.