jQuery in Action

196
CHAPTER 7
Extending jQuery with custom plugins
point out some interesting tactics that we can use when creating a somewhat com-
plex utility function.
(function($){
$.formatDate = function(date,pattern) {
var result = [];
while (pattern.length > 0) {
$.formatDate.patternParts.lastIndex = 0;
var matched = $.formatDate.patternParts.exec(pattern);
if (matched) {
result.push(
$.formatDate.patternValue[matched[0]].call(this,date)
);
pattern = pattern.slice(matched[0].length);
} else {
result.push(pattern.charAt(0));
pattern = pattern.slice(1);
}
}
return result.join('');
};
$.formatDate.patternParts =
/^(yy(yy)?|M(M(M(M)?)?)?|d(d)?|EEE(E)?|a|H(H)?|h(h)?|m(m)?|s(s)?|S)/;
$.formatDate.monthNames = [
'January','February','March','April','May','June','July',
'August','September','October','November','December'
];
$.formatDate.dayNames = [
'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday',
'Saturday'
];
$.formatDate.patternValue = {
yy: function(date) {
return $.toFixedWidth(date.getFullYear(),2);
},
yyyy: function(date) {
return date.getFullYear().toString();
},
MMMM: function(date) {
return $.formatDate.monthNames[date.getMonth()];
},
MMM: function(date) {
return $.formatDate.monthNames[date.getMonth()].substr(0,3);
},
MM: function(date) {
Listing 7.2
Implementation of the $.formatDate() utility function
Implements the main
body of the function
b
Defines the regular
expression
c
Provides the name of the months
d
Provides the name
of the days
e
Collects token-to-value
translation functions
f


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.