Does the jQuery.data () setting raise an event?

I am wondering if the call to $(".domElement").data("key", "newValue") event that I can handle? I tried change binding, but this does not work when setting data.

I think this question might ask something similar, but the changeData binding changeData not work either - jQuery data () and the changeData event .

+4
source share
2 answers

In fact, you were only trying to hook up a custom event, but you also need to call it somehow:

 $('button').click(function (e) { $('#someID').data("key", "newValue").trigger('changeData'); }); $('#someID').on('changeData', function (e) { alert('My Custom Event - Change Data Called! for ' + this.id); }); 

FIDDLE DEMO

+11
source

This was automatic, up to version 1.8.3 (determined by the source search for 'changeData').

However, it is written so that "changeData" is triggered if you do:

 $element.data('key', 'newValue'); 

but not if you pass an object, for example:

 $element.data({ 'key': 'newValue' }); 

Edited source excerpts to illustrate this:

 jQuery.fn.extend({ data: function( key, value ) { // Gets all values if ( key === undefined ) { // expurgated } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // expurgated } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, } }); 

I'm not quite sure what jQuery.access does, but it seems to me (and testing confirmed) that the event only fires if you pass the second argument to newValue.

+3
source

Source: https://habr.com/ru/post/1490290/


All Articles