Databases Reference
In-Depth Information
After a little testing, you may notice two issues. First, the main logic which sets the color and trims
the text is not executed when the page loads and the widget is initialized. Also, that same logic is
wrapped up in an event handler which was bound to the change event of the element. As a consequence,
developers have no way to execute that code without manually triggering the change event on the item,
which may be undesirable. With a little refactoring, we can solve both issues while keeping the code very
maintainable.
(function($){
$.widget("ui.lengthLimit", {
options: {
warningColor: "orange",
errorColor: "red",
maxLength: 50
},
create: function() {
var uiw = this;
this.element.change(function() {
uiw.checkLength();
});
uiw.checkLength();
},
checkLength: function() {
var uiw = this;
var $textElmt = uiw.element;
var currLength = $textElmt.val().length;
var currPercent = currLength/uiw.options.maxLength;
if (currPercent >= .9) {
$textElmt
.val($textElmt.val().substr(0, uiw.options.maxLength))
.css('color', uiw.options.errorColor);
} else if (currPercent >= .8) {
$textElmt.css('color', uiw.options.warningColor);
} else {
$textElmt.css('color', 'black');
}
}
});
})(apex.jQuery);
The majority of the logic has been moved to a new function named checkLength . This function is
used twice in the create function: once in the change event handler on the element and then later at the
end of the function.
You may have noticed that the new checkLength function didn't have the same leading underscore
that the create function did. This is an important distinction. The underscore is used to create “private”
functions within a widget. They can help modularize your code but cannot be invoked from outside the
widget. Because the checkLength function name doesn't start with an underscore, it's registered as a
public function and can be called at any time as follows:
$('#P1 FIRST NAME').lengthLimit('checkLength');
Search WWH ::




Custom Search