jQuery Custom Events 2

Check first my last post about jQuery Custom Events.

We can create a custom event with more than one handler! It is simple as this:


$("div").bind("doSomething.func1", fn1);
$("div").bind("doSomething.func2", fn2);
$("div").trigger("doSomething");

Check a little example on jsFiddle

Advertisements

jQuery Custom Events

jQuery custom events are a great feature to deal with complex situations or non trivial situations.
You can create a custom event that reacts to a particular situation that is not defined with jQuery.

You can attach a custom event just like this:


$('#someElement').on('myCustomEvent', handlerForCustomEvent)

and trigger it like this:


$('#someElement').trigger('myCustomEvent');

Note: You can also attach custom events to non DOM elements, like an object of any class for exemple.

You can see a demo of these feature in this jsFiddle.

jQuery to prevent repeat myself for a long validation form

It’s quite frustrating when we spendĀ a some time doing a jsFiddle and preparing an answer for Stack Overflow question and see the answer being removed by its user!

I’ve decided at least post it here, so that it wouldn’t be a total waste of my time.

The question was about how to reuse javascript code to perform validation of the user input.

Demo on jsFiddle

HTML code:


<input type="text" id="txtEmail"/>

<input type="button" id="btnSubmit" value="Submit" />

Javascript code:

var myValidations = function () {

  var isValidEmail = function(email){
    if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email)){
      return false;
    }
    else{
      return true;
    }
  };

  return {
    isValidEmail: isValidEmail
  }
}();

$(function(){

  $('#btnSubmit').on('click', function() {
    if(myValidations.isValidEmail($('input#txtEmail').val())){
      alert('Email is valid!');
    }
    else{
      alert('Email is not valid!');
    }
  })

})

The code above uses the Revealing Module Pattern to create a namespace for validations.
On myValidations we can add other functions to validate any user input.
In this example I have an email validation function that I can call from anywhere by passing the user input.