polymer: using a function in a data binding expression

陌路散爱 提交于 2019-12-11 02:54:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!