1/** 2* Gumby Checkbox 3*/ 4!function($) { 5 6 'use strict'; 7 8 function Checkbox($el) { 9 10 Gumby.debug('Initializing Checkbox', $el); 11 12 this.$el = $el; 13 this.$input = this.$el.find('input[type=checkbox]'); 14 15 var scope = this; 16 17 // listen for click event and custom gumby check/uncheck events 18 this.$el.on(Gumby.click, function(e) { 19 // prevent checkbox checking, we'll do that manually 20 e.preventDefault(); 21 22 // do nothing if checkbox is disabled 23 if(scope.$input.is('[disabled]')) { 24 return; 25 } 26 27 // check/uncheck 28 if(scope.$el.hasClass('checked')) { 29 scope.update(false); 30 } else { 31 scope.update(true); 32 } 33 }).on('gumby.check', function() { 34 Gumby.debug('Check event triggered', scope.$el); 35 scope.update(true); 36 }).on('gumby.uncheck', function() { 37 Gumby.debug('Uncheck event triggered', scope.$el); 38 scope.update(false); 39 }); 40 41 // update any prechecked on load 42 if(this.$input.prop('checked') || this.$el.hasClass('checked')) { 43 scope.update(true); 44 } 45 } 46 47 // update checkbox, check equals true/false to sepcify check/uncheck 48 Checkbox.prototype.update = function(check) { 49 var $span = this.$el.find('span'); 50 51 // check checkbox - check input, add checked class, append <i> 52 if(check) { 53 54 Gumby.debug('Checking Checkbox', this.$el); 55 56 $span.append('<i class="icon-check" />'); 57 this.$input.prop('checked', true); 58 59 Gumby.debug('Triggering onCheck event', this.$el); 60 Gumby.debug('Triggering onChange event', this.$el); 61 62 this.$el.addClass('checked').trigger('gumby.onCheck').trigger('gumby.onChange'); 63 64 // uncheck checkbox - uncheck input, remove checked class, remove <i> 65 } else { 66 67 Gumby.debug('Unchecking Checkbox', this.$el); 68 69 this.$input.prop('checked', false); 70 $span.find('i').remove(); 71 72 Gumby.debug('Triggering onUncheck event', this.$el); 73 Gumby.debug('Triggering onChange event', this.$el); 74 75 this.$el.removeClass('checked').trigger('gumby.onUncheck').trigger('gumby.onChange'); 76 } 77 }; 78 79 // add initialisation 80 Gumby.addInitalisation('checkbox', function() { 81 $('.checkbox').each(function() { 82 var $this = $(this); 83 // this element has already been initialized 84 if($this.data('isCheckbox')) { 85 return true; 86 } 87 // mark element as initialized 88 $this.data('isCheckbox', true); 89 new Checkbox($this); 90 }); 91 }); 92 93 // register UI module 94 Gumby.UIModule({ 95 module: 'checkbox', 96 events: ['onCheck', 'onUncheck', 'onChange', 'check', 'uncheck'], 97 init: function() { 98 Gumby.initialize('checkbox'); 99 } 100 }); 101}(jQuery); 102