How to bind an event to Can.Control to run whenever an element matching the selector is added to the control element?

断了今生、忘了曾经 提交于 2020-01-06 03:45:08

问题


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?


回答1:


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">



来源:https://stackoverflow.com/questions/27974803/how-to-bind-an-event-to-can-control-to-run-whenever-an-element-matching-the-sele

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!