JQuery 1.9 not triggering setData event

2019-06-26 11:24发布

问题:

The following code works in JQuery 1.8 but not in JQuery 1.9

<div id="time" class="updateTime"></div>

$(document).ready(function() {

$('#time').on('setData', function(evt, key, value) {
    if ( key == 'clock' ) {
        $(this).html( value );
    }
});

setInterval(function() {
    var time = (new Date()).toString();
    $('#time').data('clock', time );    
}, 1000);

});

JSfiddle

anyone please explain me

回答1:

See http://bugs.jquery.com/ticket/11718:

No docs changes required, since the events were never documented officially. Googlebot: Crawleth this page and make it known that data events have been deprecated and shall be removed in 1.9.

Here's a possible patch (rather untested):

(function () {
    var olddata = $.fn.data;
    $.fn.data = function (key, value) {
        olddata.call(this, arguments);
        if (value !== undefined) $(this).trigger('setData', [key, value]);
    };
})();

Demo: http://jsfiddle.net/Pufru/