Custom event in jQuery that isn't bound to a DOM element?

前端 未结 7 1049
迷失自我
迷失自我 2020-12-12 20:28

I\'m curious if its possible to create a custom event in jQuery that isn\'t bound to a DOM element.

I greatly prefer jQuery to YUI but there is one thing in YUI that

7条回答
  •  再見小時候
    2020-12-12 21:26

    [EDIT]

    Here's a working class that uses the concepts written below:

    https://github.com/stratboy/image-preloader

    It's just a sequential image preloader. You can subscribe to a bunch of events. Take a look.

    [/EDIT]

    Old post:

    Here's another barebones example with callbacks like suggested by Himanshu P.

    I'm building a class and I come from Mootools, where things like Classes and custom events directly implemented in classes (so not bound to DOM elements) are absolutely natural. So I tried a sort of workaround and share below.

      var step_slider;
    
      //sandbox
      ;(function($) {
    
    //constructor
    var StepSlider = function(slider_mask_selector,options) {
    
        //this.onStep = $.Event('step');
        this.options = null;
        this.onstep = $.Callbacks();
    
        this.init();
    }//end constructor
    
    StepSlider.prototype = {
    
        init:function(){
            this.set_events();
        },//end init
    
        set_events:function(){
    
            if(this.options){
                if(this.options.onstep){
                    this.subscribe('step',options.onstep);
                }
            }
    
        },//set_events
    
        subscribe:function(event,action){
            this['on'+event].add(action);
        },
    
        fire_onstep:function(){
            this.onstep.fire({ data1:'ok' });
        }
    
    }//end prototype/class
    
    //--------------------
    
    $(document).ready(function() {
    
        step_slider = new StepSlider('selector');
    
        //for example, say that you have a div#next-button, you can then do this:
        $('#next-button').click(function(){
            step_slider.fire_onstep();
        });
    
    });//end domready
    
    
    })(jQuery);
    

提交回复
热议问题