I am to create an inbox messages drop down like this,
were the relative time of the message gets displayed via moment JS. The following snippet below shows the final result. but the problem with this code is that the time which is in milliseconds does not get updated at interval to show the relative time of the milliseconds with the present date. So i tried using set interval inside the method.
Non Set interval Example (works fine, but the final converted time doesnt change after being changed the first time)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<table>
<thead>
<tr><th>First name</th><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<!-- ko if: ($index() < 5) -->
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: message"></td>
<td data-bind="text: $root.converttime(dateCreated)"></td>
</tr>
<!-- /ko -->
</tbody>
</table>
<script type="text/javascript">
var viewmodel = {
people: ko.observableArray([
{ firstName: 'Bert', message: 'Bertington', dateCreated:1540887096175 },
{ firstName: 'Charles', message: 'Charlesforth',dateCreated:1540887096175 },
{ firstName: 'Author', message: 'Dentiste', dateCreated:1540887096175 }
])
};
viewmodel.converttime = function (milliseconds){
return moment(milliseconds).fromNow();
};
ko.applyBindings(viewmodel);
</script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…