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 set.
I think this question may be asking something similar, but binding changeData
didn't work either - jQuery data() and 'changeData' 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 set.
I think this question may be asking something similar, but binding changeData
didn't work either - jQuery data() and 'changeData' event.
-
4
I don't think it triggers an event, if you want then you can trigger a custom event, ex
$(".domElement").data("key", "newValue").trigger('changeData')
– Arun P Johny Commented Jul 8, 2013 at 13:47 -
Ok thanks, so then how can I access the original element that triggered the event? Usually I'd just use
$(this)
in the handler but it's showing up asundefined
. – Matt Commented Jul 8, 2013 at 13:57 -
@Matt Look at the docs for
trigger
. You won't be able to setthis
, but you can pass extra parameters that you can get in the handler – Ian Commented Jul 8, 2013 at 14:00 -
Actually forget that -
$(this)
works fine when I bind my handler to the specific selector rather than just $(document). – Matt Commented Jul 8, 2013 at 14:03
2 Answers
Reset to default 12Actually 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);
});
FIDDLE DEMO
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 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 pletely 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.