I am currently writing my first jQuery plugin and I am struggling to find an appropriate way to structure the code. I have read the documentation on the jquery website as well as the source code for other plugins, but can’t seem to find an agreed way of doing it or one that addresses the issue I am having.
The plugin adds some text processing to a text input element to format text as a date.
The example below binds two events to the element. The issue I have is how can I access the element itself from the _processText function. In the example I use $(this), but this gives me the object, not the element so I can’t set the value on it or trigger an event. The only way I have found to do it is to pass the element into the function as a parameter directly in the bind event, but I don’t think that look correct.
Any help greatly received.
(function($) {
var methods = {
init : function( options ) {
return this.each(function() {
// Process the entered text and convert
// into a formatted date
$(this).bind('blur', function(event){
methods._processText($(this).val());
});
// Custom event to trigger when invalid text
// is entered
$(this).bind('invalid', function(event) {
alert("Invalid");
});
});
},
_processText: function(txt) {
// Sudo code
if (txt.isValid()) {
$(this).val(txt)
} else {
$(this).trigger("invalid");
}
}
};
// boilerplate
$.fn.datefield = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.DateField' );
}
};
})(jQuery);
Use this:
Then inside the
_processTextmethod,thiswill point to the jQuery object.Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call