简体   繁体   中英

Trigger a jQuery custom event set by different instance

Is there any way to trigger custom events set by a different jQuery instance? For example:

// Load version 1.9.1
...
jQuery191(document).on('customEvent', function () {console.log('Callback fired.')});

// Load version 1.6.2 and setup noConflict
...
jQuery162(document).trigger('customEvent');

While it's not recommended to load more than one version of the library, a simple use-case is a plugin that pulls in a specific version of jQuery if the current instance is lower than expected. Any suggestions?

You should really take care if you have different instance (even if the same version) on a page, because this could lead to unexpected behavior and could result in memory leaks, eg if you remove an element with jQuery191 that has data ( .data(...) or event listeners) that was stored with jQuery162 this will remain in memory until you reload the page and the other way round.

But back to your question. I would not recommend it but you could double the event (trigger it with both versions). The problem with this approach is that it would slow down everything. And the other problem is that you have two bubbling phases. So if you prevent the event in jQuery191 it will still be executed in jQuery162 and the other way round.

So it could be a solution that works for you, but it could also make the things worser. So you need to check your self if this solution is something you can use. Probably you also can remove one of the doubling parts.

(function() {
    //keep the original functions
    var trigger191 = jQuery191.fn.trigger;
    var trigger162 = jQuery162.fn.trigger;

    jQuery191.fn.trigger = function( evt ) {
        trigger191.apply(this,arguments); //call orginal function

        //only double certain events
        if( evt == "my-custom-event" ) {
            var resultset162 = jQuery162(jQuery191.makeArray( this ));//create a ne result set of the 162 version
            trigger162.apply(resultset162,arguments); //call the original function of 162 to avoid an endless loop
        }
    };

    jQuery162.fn.trigger = function(evt) {
        trigger162.apply(this,arguments); //call orginal function

        //only double certain events
        if( evt == "my-custom-event" ) {
            var resultset191 = jQuery191(trigger162.makeArray( this ));
            trigger191.apply(resultset191,arguments); //call the ofiginal function of 191 to avoid an endless loop
        }
    };

})();

(I hope the code works that way. I pretty sure it should work, but I can't test it right now)

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