Adding Functions to jQuery - PHP and Jquery

In some cases, it may be desirable to add a function directly to the jQueryobject, which means youwould be able to call it like so:

$.yourFunction();

Adding functions to jQuery can help you keep your scripts organized and ensure that your function calls follow a consistent format. However, it’s important to note that adding a function to jQuerydoesnot allow you to chain it with a set of selected DOM elements; for this, you must use a method, which you’ll learn how to do in this chapter.

Adding Your Date Validation Function to jQuery

In your first extending jQuery example, you will add the date validation function you wrote in the last chapter to the jQueryobject. Specifically, you’ll leverage valid-date.js.

Allowing Custom Aliases in jQuery Plugins

One thing you should consider is allowing custom aliases in your jQuery plugins. While this isn’t strictly necessary, it is strongly encouraged because it can help you keep your plugin from breaking if the $shortcut is given up by jQuery.noConflict(). Better still, this feature is so simple to implement that it’s actually a little silly not to include it.

When building a new plugin, youshould put the plugin code within a function that is executedimmediately when the script is loaded. At its outset, the script should look like this:

(function(){
// plugin code here...
})();

The second set of parentheses causes the preceding code to be executed immediately as a function, which is where the custom alias comes in. If you pass the jQueryobject to the second set of parentheses and the $ shortcut to the internal function, then the code will work properly with the $ shortcut, even if it’s given back to the global namespace using

jQuery.noConflict():
(function($){
// plugin code here...
})(jQuery);

ou could use any valid JavaScript variable name in place of the $, and the script would still execute properly with this method:

(function(custom){
// Adds a background color to any paragraph
// element using a custom alias
custom("p").css("background-color","yellow");
})(jQuery);

Attaching the Function to the jQuery Object

To attach the function to jQuery, you can add the following code to valid-date.js:

(function($){
// Extends the jQuery object to validate date strings
$.validDate = function()
{
// code here
};
})(jQuery);
Using this format, you now call the validDate() function like this:
$.validDate();

Allowing Configurable Options

Just as in the original validDate() function, a date string will be passed into the function. However, to make this function more configurable, you can pass in an object containing configuration options (if necessary) to modify the regex pattern used to match the date string:

(function($){
// Extends the jQuery object to validate date strings
$.validDate = function(date, options)
{
// code here
};
})(jQuery);

The options object will only have one property: the pattern to be used for validation. Because you want the options object to be optional, you define a default value for the pattern in the function by inserting the following bold code:

(function($){
// Extends the jQuery object to validate date strings
$.validDate = function(date, options)
{
// Sets up default values for the method
var defaults = {
"pattern" : /^d{4}-d{2}-d{2}sd{2}:d{2}:d{2}$/
};
};
})(jQuery);

Extending Default Options with User-Supplied Options

You can extend the default object using the $.extend() function, which will create a new object by combining the default options with the user-supplied options. If there are three options available and the user passes an object with only two of them defined, using $.extend() will only replace the two properties redefined by the user.Insert the code shown in bold to extend the default object:

(function($){
// Extends the jQuery object to validate date strings
$.validDate = function(date, options)
{
// Sets up default values for the method
var defaults = {
"pattern" : /^d{4}-d{2}-d{2}sd{2}:d{2}:d{2}$/
},
// Extends the defaults with user-supplied options
opts = $.extend(defaults, options);
};
})(jQuery);

Performing Validation and Returning a Value

This step is nearly identical to one in the original function, except you access the pattern here through the optsobject:

(function($){
// Extends the jQuery object to validate date strings
$.validDate = function(date, options)
{
// Sets up default values for the method
var defaults = {
"pattern" : /^d{4}-d{2}-d{2}sd{2}:d{2}:d{2}$/
},
// Extends the defaults with user-supplied options
opts = $.extend(defaults, options);
// Returns true if a match is found, false otherwise
returndate.match(opts.pattern)!=null;
};
})(jQuery);

Conforming to jQuery Plugin File Naming Conventions

To officially call a plugin a plugin, you must use the jQuery naming conventions for your plugin files. The accepted format is jquery.[name of plugin].js—to meet this guideline, change the name of validdate.jsto jquery.validDate.js.

Modifying the Include Script

Now that the file name has changed, you need to update footer.inc.phpto include it. Make the changes shown in bold to load the correct file:

<script type="text/javascript"
src="http://www.wisdomjobs.com/jsapi"></script>
<script type="text/javascript">
wisdomjobs.load("jquery", "1");
</script>
<script type="text/javascript"
src="assets/js/jquery.validDate.js"></script>
<script type="text/javascript"
src="assets/js/init.js"></script>
</body>
</html>

Modifying the Initialization Script

Finally, adjust init.js to call the new jQuery function you’ve just added by making the adjustments shown in bold:

jQuery(function($){
varprocessFile = "assets/inc/ajax.inc.php",
fx = {...}
$("li a").live("click", function(event){...});
$(".admin-options form,.admin")
.live("click", function(event){...});
// Edits events without reloading
$(".edit-form input[type=submit]").live("click", function(event){
// Prevents the default form action from executing
event.preventDefault();
// Serializes the form data for use with $.ajax()
varformData = $(this).parents("form").serialize(),
// Stores the value of the submit button
submitVal = $(this).val(),
// Determines if the event should be removed
remove = false,
// Saves the start date input string
start = $(this).siblings("[name=event_start]").val(),
// Saves the end date input string
end = $(this).siblings("[name=event_end]").val();
// If this is the deletion form, appends an action
if ( $(this).attr("name")=="confirm_delete" )
{
// Adds necessary info to the query string
formData += "&action=confirm_delete"
+ "&confirm_delete="+submitVal;
// If the event is really being deleted, sets
// a flag to remove it from the markup
if ( submitVal=="Yes, Delete It" )
{
remove = true;
}
}
// If creating/editing an event, checks for valid dates
if ( $(this).siblings("[name=action]").val()=="event_edit" )
{
if ( !$.validDate(start) || !$.validDate(end) )
{
alert("Valid dates only! (YYYY-MM-DD HH:MM:SS)");
return false;
}
}
// Sends the data to the processing file
$.ajax({
type: "POST",
url: processFile,
data: formData,
success: function(data) {
// If this is a deleted event, removes
// it from the markup
if ( remove===true )
{
fx.removeevent();
}
// Fades out the modal window
fx.boxout();
// If this is a new event, adds it to
// the calendar
if ( $("[name=event_id]").val().length==0
&& remove===false )
{
fx.addevent(data, formData);
}
},
error: function(msg) {
alert(msg);
}
});
});
$(".edit-form a:contains(cancel)")
.live("click", function(event){...});
});

After saving the preceding code, you can reload http://localhost/ and try to submit a new event with bad date values. The result is identical to the result obtained when using the original validDate()function.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP and Jquery Topics