jQuery widgets and variable scope
I am trying to build a simple widget/plugin for jQuery for a project I am working on. However I seem to be hitting my head against a brick wall currently.
-
(function($) {
$.fn.validation = function(options) {
// define defaults and override with options, if available
// by extending the default settings, we don't modify the argument
// do the rest of the plugin, using url and settings
return this.each(function() {
var settings = jQuery.extend({
vg: "",
vt: ",
errorMessage: ""
}, options);
if ($(this).is("input") || $(this).is("select")) {
$(this).attr("vg", options.vg);
if (options.vt != null)
$(this).attr("vt", options.vt);
if (options.error != null)
$(this).attr("error", options.error);
$(this).bind("isValid", IsValid);
if ($(this).is(":submit") || $(this).is(":button")) {
$(this).click(ValidationClick);
return;
}
$(this).focus(GetFocus);
$(this).blur(RemoveFocus);
};
$.fn.validation.errorMessages = function(){ return settings.errorMessage; };
});
};
})(jQuery);
Above is the code I have written, and it seems to work well, until I get to the point I want to retrieve my error messages.
The code currently assigns the attributes to the object, first making sure its an HTML Input element. And thats fine, but I want to start to change things around so that its properties in an object within the element.
I want to be able to call the function validation.errorMessages() and get from the settings object the array of the error messages. However everytime I call the method, the settings variable that is being accessed is the last element that was called:
-
$("#username").validation({ vg: "acc", vt: "req", error: ["Enter a username"] });
$("#firstname").validation({ vg: "acc", vt: "req", error: ["Enter your first name"] });
$("#lastname").validation({ vg: "acc", vt: "req", error: ["Enter your last name"] });
But when I call $("#username").validation.errorMessages() I get the error messages from $("#lastname").
Anyone know what am doing wrong?