Updating timeago when date is not changing


#1

One of my students has a page that displays createdAt date using moment.js in “time ago” format. Because the createdAt date does not change, the display does not change. So “25 minutes ago” remains “25 minutes ago” even when it’s 45 minutes ago.

What is the best practice for updating this? My first thought was to create a computed property called timego (perhaps on the controller) and another called “checked” and set to true or false. In it I’d use moment to set the timeago text. Then I might use a timeout to alternately toggle the “checked” property back and forth between true and false, say once a minute.

That way the computed property would see the change in the checked property and update the view even though the createdAt property remains the same.

Is there a better way to do this? Maybe by causing the computed property to recalculate directly?


#2

Here’s a quick example of how you might do this: http://jsbin.com/ihinar/1/edit

The idea here is that a given property in a Handlebars template will update if you call notifyPropertyChange('propName').

You might need to be a little careful with this if you end up with hundreds of properties like this; in particular, you want to turn off the property invalidation if it is not being displayed in the DOM. But for most cases, you can just blindly invalidate and it should be fine.


#3

Ha! This is exactly what I was looking for. Didn’t know about Ember.run (though vague memory of some sort of event machine discussion a year ago) or notifyPropertyChange. This will be a huge help (and as I’m trying to teach my students some Ember, not just to me). Thanks!


#4

I wrote a slightly more specialised answer to this question, then realised @tom had already answered it succinctly. Posting it here for everyone’s reference and/or amusement anyways.


#5

Awesome. Thanks, Jamie.


#6

Thanks, yours is way better. :slight_smile:


#7