In most cases, triggering a change event when a property is updated should be the accepted answer, however there are some cases where the properties are adjusted and you donβt have the luxury to add a trigger function call. A common example is when a script is placed outside.
The snippet below will use the current jQuery support function to retrieve and / or change the value of a property, but it will also trigger two events: one before the property changes and the other after the property has been changed. Both the property name and the variable value will also be passed.
jQuery(function(){ var _oldProp = jQuery.fn.prop; jQuery.fn.extend({prop: function( prop, val ) { // Only trigger events when property is being changed if ( val !== undefined ) { this.trigger( 'propChange', [prop, val] ); // before change listener var oldVal = this.prop( prop ); // Get old Value var ret = _oldProp.call( this, prop, val ); // Update Property this.trigger( 'propChanged', [prop, oldVal] ); // after change listener return ret; } return _oldProp.call( this, prop ); }}); });
Then, to capture the change event, you can bind it to any listener and even compare the name of the property and the old value (or the new value if you are connecting to the previous event) as necessary.
jQuery('input[type="checkbox"]').on('propChanged', function( event, prop, oldVal ) { if ( prop === 'checked' && oldVal !== jQuery(this).prop( prop ) ) { jQuery(this).trigger('change'); } });
This can be used for any property, and is not limited to flags and change events. The same fragment above can also be copied to work with the jQuery(el).attr(attr,val) function.
Shaun Cockerill Mar 01 '17 at 4:43 on 2017-03-01 04:43
source share