From ef223608a31e487001006ea03776024cf46622cd Mon Sep 17 00:00:00 2001 From: Brahim Arkni Date: Fri, 12 Feb 2016 16:50:34 +0000 Subject: [PATCH] Core: Bind the `blur` event just once in `equalTo` rule bind the event just once, avoiding the unbind-rebind overhead. Also, unbind it when destroying the plugin. Ref #1704 Ref #1707 --- src/core.js | 10 ++++++---- test/test.js | 18 ++++++++++++------ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/core.js b/src/core.js index 4ccbac3ce..281d5268e 100644 --- a/src/core.js +++ b/src/core.js @@ -1061,7 +1061,10 @@ $.extend( $.validator, { $( this.currentForm ) .off( ".validate" ) - .removeData( "validator" ); + .removeData( "validator" ) + .find( ".validate-equalTo-blur" ) + .off( ".validate-equalTo" ) + .removeClass( "validate-equalTo-blur" ); } }, @@ -1386,10 +1389,9 @@ $.extend( $.validator, { equalTo: function( value, element, param ) { // Bind to the blur event of the target in order to revalidate whenever the target field is updated - // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead var target = $( param ); - if ( this.settings.onfocusout ) { - target.off( ".validate-equalTo" ).on( "blur.validate-equalTo", function() { + if ( this.settings.onfocusout && target.not( ".validate-equalTo-blur" ).length ) { + target.addClass( "validate-equalTo-blur" ).on( "blur.validate-equalTo", function() { $( element ).valid(); } ); } diff --git a/test/test.js b/test/test.js index c177c8cf5..0ed3d4500 100644 --- a/test/test.js +++ b/test/test.js @@ -2150,15 +2150,21 @@ test( "Validation triggered on radio and checkbox via click", function() { } ); test( "destroy()", function() { - expect( 2 ); + expect( 6 ); + + var form = $( "#testForm5" ), + validate = form.validate(); - var form = $( "#form" ), - validate = form.validate(); + strictEqual( form.data( "validator" ), validate ); - strictEqual( $( form ).data( "validator" ), validate ); + form.valid(); + equal( $( "#x1", form ).hasClass( "validate-equalTo-blur" ), true, "The blur event should be bound to this element" ); + equal( $( "#x2", form ).hasClass( "validate-equalTo-blur" ), true, "The blur event should be bound to this element" ); - validate.destroy(); - strictEqual( $( form ).data( "validator" ), undefined ); + validate.destroy(); + strictEqual( form.data( "validator" ), undefined ); + equal( $( "#x1", form ).hasClass( "validate-equalTo-blur" ), false, "The blur event should be unbound from this element" ); + equal( $( "#x2", form ).hasClass( "validate-equalTo-blur" ), false, "The blur event should be unbound from this element" ); } ); test( "#1618: Errorlist containing more errors than it should", function() {