简体   繁体   中英

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 set.

I think this question may be asking something similar, but binding changeData didn't work either - jQuery data() and 'changeData' event .

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);
});

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM