Is it appropriate to create jQuery plugins which are specific to a single page? I've been creating generic plugins that are not tied to any context and contain no business logic, but some people I've talked to suggest that almost all javascript, including business logic and logic specific to a single p开发者_高级运维age, should be inside of jQuery plugins.
Is it appropriate to have a validateformXYZ plugin which validates a specific HTML form?
I'm buying into jQuery 100% but am not sure if this is a misuse or not.
I tend to use a different approach to this. When I have objects (forms, usually) that need to have a lot of client-side behavior bound to them, I define JavaScript objects that represent those forms.
For example, a contact form might have a corresponding Contact object that gets initialized with the context of the inner-form elements (textboxes, buttons, etc.) During initialization you can then use jQuery (or your framework of choice) to add behaviors to these elements. In your case you'd bind a click event which would call a validation function in your Contact object.
This seems cleaner than creating a whole bunch of unrelated plugins to provide very specific behavior.
EDIT TO PROVIDE EXAMPLE
Here's a quick & simple sample of this in action: http://jsbin.com/elefi/edit
The code:
if(typeof(MyDomain) == "undefined") {
MyDomain = {};
MyDomain.MyApp = {};
}
MyDomain.MyApp.ContactForm = function() {
var $_submitButton;
var $_firstNameTextBox;
var _validateForm = function () {
if($_firstNameTextBox.val() === '') {
alert('Form Invalid');
}
else {
alert('Form Valid');
}
};
return {
initialize: function(submitButtonId, firstNameTextBoxId) {
// Add context
$_submitButton = $("#" + submitButtonId);
$_firstNameTextBox = $("#" + firstNameTextBoxId)
// Add behaviours
$_submitButton.click(_validateForm);
}
}
}();
// Emit this using your server-side code
$(function() {
MyDomain.MyApp.ContactForm.initialize('SubmitButton', 'FirstName');
});
Note that IE6 seems to dislike jsbin.com, so open it in FF
To be honest, it's up to the implementation, as long as it gets the job done, and IMHO adheres to the DRY principle.
The fact that something is a plug-in can even imply in more code to be written just to make a method a plug-in.
Web scripting, even if you aren't using a formal multi-tier architecture, is inherently multi-tier. In this case, JavaScript is running on the View (or UI), and shouldn't be doing complex business logic.
In addition to UI manipulation and sending/receiving data from the next application tier, because of how decoupled web applications are, JavaScript should be doing some basic validation. This validation should be repeated in one of the other tiers, as JavaScript can be disabled.
By basic validation, I mean if values are filled in, are the correct type, etc... Minimum/Maximum should not be validated unless they are explicitly placed under the UI's control... otherwise you run the risk of getting things out of sync with the other tiers.
精彩评论