I am creating a Polymer web component that leverages moment.js. I create a computed binding that takes in a date and returns a string formatted by moment.js. Problem is, sometimes this method is run before the app loads the moment.js library resulting in a variable undefined error. Is there a way I can wait to return a value to the view or delay when the computing function gets called?
Please see below for code example:
<span>{{computedDate(date)}}</span>
<script>
Polymer({
...
computedDate: function(date) {
return moment(date, "MM-DD-YYYY").fromNow()
}
})
</script>
If you want to be certain moment.js is loaded you could load it dynamically & wait for the load event to fire:
var script = document.createElement('script');
script.src = path/to/moment.js;
script.onload = function () {
//here you know moment.js is loaded, so set the loaded "flag" to true
};
document.head.appendChild(script);
Then in your computed binding watch for changes to the loaded flag, only using moment when it's true:
<span>{{computedDate(date, loaded)}}</span>