Does Setting Jquery.data() Trigger An Event?
I'm wondering if calls to $('.domElement').data('key', 'newValue') will trigger an event that I can handle? I've tried binding change but this doesn't get triggered when data is se
Solution 1:
Actually you have only tried to attach the custom event but you will also have to trigger it something like:
$('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);
});
Solution 2:
It was automatic, up until version 1.8.3 (determined by searching the source for 'changeData').
However, it's written such that 'changeData' is triggered if you do:
$element.data('key', 'newValue');
but not if you pass an object, like:
$element.data({
'key': 'newValue'
});
Edited source excerpts to illustrate this:
jQuery.fn.extend({
data: function( key, value ) {
// Gets all valuesif ( key === undefined ) {
// expurgated
}
// Sets multiple valuesif ( typeof key === "object" ) {
returnthis.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 completely sure what jQuery.access does, but it looks to me (and testing confirmed) that the event only gets fired if you have passed the second 'newValue' argument.
Post a Comment for "Does Setting Jquery.data() Trigger An Event?"