Romain F.
Romain F.

Reputation: 794

Applying JQuery-UI datepicker in a template before it is added to the DOM

I am trying to apply a datepicker every inside a template, then add that template to the DOM. I was able to do it by adding the template to the DOM first (using $.each), but I am separating the responsibilities now (using Backbone) and I need it done in that order. I tried to use replaceWith in the context of my template :

$("input[type=date]", template).replaceWith(function() {
    $(this).datepicker({dateFormat : "yy-mm-dd"});
    return this.outerHTML;
});
return Mustache.render(template, this.model.toJson);

but template is not updated, and replaceWith only returns an array with my updated inputs. I feel the answer is not far, but I'm stuck here. I can render the template with Mustache before or after applying the datepickers, this is not a problem.

Any ideas ?

Upvotes: 0

Views: 1318

Answers (1)

mu is too short
mu is too short

Reputation: 434755

Mustache.render is going to return some HTML based on the template in template and data in this.model.toJson (which should be this.model.toJSON(), no?). All the jQuery UI stuff and jQuery events are bound to DOM elements, not HTML text so it doesn't matter what you bind to template, none of it will survive going through Mustache.

You need to bind everything to the output of Mustache.render. Something more like this:

render: function() {
    var template = ...
    var html = Mustache.render(template, this.model.toJSON());
    this.$el.append(html);
    this.$('input[type=date]').datepicker({dateFormat: 'yy-mm-dd'});
    return this;
}

and then whatever called render would $something.append(v.render().el).

Upvotes: 2

Related Questions