我想实现这个插件使用jQuery:
https://github.com/rmm5t/jquery-timeago
https://github.com/rmm5t/jquery-timeago
该插件的简短描述:
这将通过一系列时间和ISO来转换所有的abbr元素
8601标题中的时间戳(符合datetime设计模式
微格式):
<abbr class="timeago" title="2011-12-17T09:24:17Z">December 17,2011</abbr>
像这样的东西:
<abbr class="timeago" title="December 17,2011">about 1 day ago</abbr>
除了使用knockout,我的标记如下所示:
<abbr data-bind="attr: { title: Posted }" class="timeago"></abbr>
我认为有些东西没有被同步,因为没有任何事情发生,即使我在viewmodel本身内调用了时间.我猜想我需要一个附加到可观察的“发布”的订阅者,但我不知道如何设置.
解决方法
您的方法不起作用,因为timeago通过jQuery的data()函数创建一个缓存.因此,简单地更新标题是不够的.
我认为自定义绑定是最好最干净的方式:
ko.bindingHandlers.timeago = { update: function(element,valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); var $this = $(element); // Set the title attribute to the new value = timestamp $this.attr('title',value); // If timeago has already been applied to this node,don't reapply it - // since timeago isn't really flexible (it doesn't provide a public // remove() or refresh() method) we need to do everything by ourselves. if ($this.data('timeago')) { var datetime = $.timeago.datetime($this); var distance = (new Date().getTime() - datetime.getTime()); var inWords = $.timeago.inWords(distance); // Update cache and displayed text.. $this.data('timeago',{ 'datetime': datetime }); $this.text(inWords); } else { // timeago hasn't been applied to this node -> we do that now! $this.timeago(); } } };
用法和这样简单:
<abbr data-bind="timeago: Posted"></abbr>