1

I am trying to build a DateTimePicker Widget and do not want to worry about the instantiation of the widget so I have created a Can.Control which takes the html body as the element.

But, now my input elements are rendered in the DOM using can.view. How do I bind an event to the insertion of a new dateTime element to my control scope?

/**
 * DateTime Plugin
 */

plugins.DateTime = can.Control.extend({

},{
    init : function ( element , options ){
    },

    'input.dateTime click' : function (){
        $( this.element ).find('input.dateTime').datetimepicker();
    }
});
$(function(){
    new plugins.DateTime('body');
});

Is there any way I can specify 'input.dateTime load' to bind a datepicker when the element is added to the control element?

Neil DCruz
  • 195
  • 2
  • 13

1 Answers1

0

There are a few ways to do this, for example, your can.view-based rendering can perform a callback after it's finished, so you can do: var that = this; can.view(template, data, function() { that.element.find("input.dateTime").datetimepicker(); }

But that's not really what I'd recommend. The previous example doesn't account for any case when one of those fields has to be redrawn because of data changes after the first rendering of the view. Instead, create a helper as such: Mustache.registerHelper("datetimepicker", function() { return function(el) { $(el).datetimepicker(); } });

Then in your (Mu)Stache file:

<input type="text" name="datetime_start" class="dateTime" {{datetimepicker}} can-value="datetime_start">

air_hadoken
  • 611
  • 4
  • 5
  • Thanks! Your second suggestion makes sense but, my entire application html is not rendered using a mustache renderer for which I will still have to bind the datetimepicker seperately. The control seemed like the best option to me since i would not have to keep track of bindings as long as the elements are within my control scope. Ive seen some suggestion about using control.on but couldnt understand how to apply it to my situation. – Neil DCruz Jan 16 '15 at 08:35
  • It's tricky because the "inserted" event (CanJS event when an element is attached to the DOM) doesn't bubble, so you can't listen for it in a delegate. Otherwise you could do `this.on("inserted", "input.dateTime", function(el, ev) { ... })`. One way around this is to use a MutationObserver, because those will catch matches added below the bound element; alternately you could use a Mustache helper that binds to "inserted" directly on the element to be added, then sends a synthetic event that does bubble (e.g. "datetimeinserted"). Neither of these are necessary with the methods outlined above – air_hadoken Jan 17 '15 at 03:53