jQuery plugin create custom event -
i'm starting doing jquery plugins don't have experience doing it, thing want have done today create custom event plugin i'm working on.
i thing example show exact want bootstrap tooltip plugin, plugin can that:
$('.my-tooltip').tooltip('show');
forcing plugin action, in case execute show()
plugin function
for specific case i'm doing plugin custom validate forms around website using jquery validate plugin , wan't like:
$('form#whatever').validateform('showinlinechecks');
to force plugin run validation specific fields.
let's take of code:
/* * jquery plugin validate forms around segurosdigitales * requires jquery validate plugin * */ if( typeof object.create !== 'function' ){ object.create = function( obj ) { function f(){}; f.prototype = obj; return new f(); } } (function($){ var validator = { // init plugin init: function(options, element){ var self = this; self.options = $.extend( {}, $.fn.validateform.options, options ); self.elem = element; self.$elem = $(element); self.validatetheform(); }, // set default options jquery validate plugin setvalidationoptions: function(){ var self = this; // default options forms around app // these default options jquery validate plugin var jqueryvalidatepluginoptions = { onfocusout: function(e){ // validate elements when 'blur' event happens, except if has 'datepicker-open' class, i'm adding class because datepicker causes input element loses focus , validation error triggered if(!$(e).hasclass('datepicker-open')){ this.element(e); } }, errorelement: 'span', errorclass: 'error help-block', errorplacement: function(error, element){ if(element.is('input[type="checkbox"]')){ error.insertafter(element.parent()); } else { error.insertafter(element); } }, // highlight occurs when element has erros highlight: function(element, errorclass, validclass){ $(element).addclass(errorclass).removeclass(validclass); var control_group = $(element).closest('.control-group, .controls-row'); control_group.addclass(errorclass).removeclass(validclass); // remove valid icon control_group.find('i.icon-ok').remove(); }, // unhighlight occurs when element valid unhighlight: function(element, errorclass, validclass){ $(element).removeclass(errorclass).addclass(validclass); // parent of field var control_group = $(element).closest('.control-group, .controls-row'); // field empty? var element_is_empty = ( $(element).val() === '' ); if (!element_is_empty && !control_group.find('i.icon-ok').length) { var label = control_group.find('label'); // prevent add more 1 icon if control group contains more 1 label (ie. when have checkboxes , radio buttons) $.each(label, function () { $(this).prepend('<i class="icon-ok green"></i>'); return false; }); // add class if element valid , not empty control_group.removeclass(errorclass).addclass(validclass); } } }; // add other options depending of validateform plugin options if( self.options.errormessages ){ jqueryvalidatepluginoptions.messages = self.options.errormessages; } if( self.options.rules ){ jqueryvalidatepluginoptions.rules = self.options.rules; } if( self.options.shownotification ){ jqueryvalidatepluginoptions.invalidhandler = function(event, validator){ var errors = validator.numberofinvalids(); if(errors){ generatenotification('error', false, 'por favor corrige los errores en los campos resaltados en rojo para poder continuar.'); } } } return jqueryvalidatepluginoptions; }, // validate form validatetheform: function(){ var self = this; var validateopts = self.setvalidationoptions(); self.$elem.validate(validateopts); } }; $.fn.validateform = function(options){ return this.each(function(){ var validate = object.create(validator); validate.init(options, this); }); }; $.fn.validateform.options = { errormessages: null, rules: null, shownotification: true } })(jquery);
how can it?
creating, emitting , subscribing custom events quite simple jquery.
in order emit custom event call trigger
$(elem).trigger('mycustomevent.myns')
i recommend useing namespaces, easier managing custom events
then subscribe event regular event
$(elem).on('mycustomevent.myns', function(event) { })
you can add additional parameters passed event handler, that
$(elem).trigger('mycustomevent.myns', ['p1', 'p2']) $(elem).on('mycustomevent.myns', function(event, param1, param2) { console.log(param1) // outputs p1 console.log(param2) // outputs p2 })
so overall , on user actions , clicking button, you'll emit custom event, this
$(elem).on('click', 'button.save', function (e) { $(elem).trigger('validate.myctrl', [e, this]) })
also note in case event has same name method on object defining events on, jquery try call method when calling
trigger
. avoid behavior usetriggerhandler
jquery method.
update: @cristiangrojas, recomend check different "standard" ways of setting jquery plugin here https://github.com/shichuan/javascript-patterns/tree/master/jquery-plugin-patterns'
Comments
Post a Comment