Steve
Steve

Reputation: 5166

How to apply jQuery timeago or easydate on Backbone / Underscore?

How do you apply timeago or easydate on <time class="prettydate"><%= created_at %></time>" (which outputs something like this Mon Jun 18 03:46:27 +0000 2012)?

I tried the below but it doesn’t work because I am using Backbone / Underscore to render the date.

$(function() {
  $('time.prettydate').easydate();
});

Here is my view:

( function ( views ){

    views.ResultView = Backbone.View.extend({
        tagName : 'li',
        template: _.template($('#resultItemTemplate').html()),

        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('destroy', this.remove, this);
        },

        render : function () {
            //this.$el.html(this.template(this.model.toJSON()));
            var html = this.template(this.model.toJSON());
            this.$el.html($(html).timeago());
        }
    });

})( app.views );

Upvotes: 1

Views: 965

Answers (1)

mu is too short
mu is too short

Reputation: 434755

Presumably you have something like this in a view:

render: function() {
    var html = _.template(...);
    this.$el.append(html);
    return this;
}

All you need to do is apply the plugin straight to html while you're appending it:

render: function() {
    var html = _.template(...);
    this.$el.append($(html).timeago());
    return this;
}

Demo: http://jsfiddle.net/ambiguous/Fk6xF/

This works equally well if you're doing this.$el.html(...).

If the pieces that you need to apply timeago to are inside your template, then you'll have to hunt them down and apply .timeago() to the individually. Something like this should do the trick:

render: function() {
    var html = _.template(...);
    this.$el.html(html);
    this.$el.find('.timeago').timeago(); // Assuming you're using class="timeago"
    return this;
}

Demo: http://jsfiddle.net/ambiguous/dHr6D/

Upvotes: 4

Related Questions