问题
One of the properties of my Polymer element is a timestamp:
Polymer({
timestamp: null,
ready: function () {
this.timestamp = new Date().getTime();
}
});
In my markup I need to show a formatted timestamp:
<template>
timestamp={{getFormattedTimestamp()}}
</template>
where
getFormattedTimestamp: function () {
return new Date(this.timestamp).toLocaleString('en-US', {timeZoneName: 'short'});
}
But the code above does not update the display when this.timestamp changes because Polymer does not know that it needs to call getFormattedTimestamp when this happens.
I cannot just put the contents of getFormattedTimestamp into the data binding expression because it won't be able to parse it, and I cannot create a computed property either for the same reason.
Is there a way to do it other than creating an auxiliary member variable that holds the formatted timestamp and updating it when the timestamp changes?
回答1:
Did you look into filter expressions ?
You can have something like this:
<template>
timestamp={{timestamp | getFormattedTimestamp }}
</template>
回答2:
Functions in markup have to refer to the properties they depend on in as their parameters (because Polymer uses these to figure out when to update them).
<template>
timestamp={{getFormattedTimestamp(timestamp)}}
</template>
getFormattedTimestamp: function (timestamp) {
return new Date(timestamp).toLocaleString('en-US', {timeZoneName: 'short'});
}
来源:https://stackoverflow.com/questions/27159625/polymer-using-a-function-in-a-data-binding-expression