Is there a way to bind a command to fadeIn event w

2019-05-08 19:27发布

I have an interactive form system that has different modules, where the forms for each module is contained inside a different div element. When i change from one module to another, I often do this:

$('#module_1').hide();
$('#module_2').fadeIn();

I like this, but now, after developing this system for some time, I have some functions (like re-initialize a jqgrid) that I want to happen every time a fadeIn occurs. I set up this up like this:

$('#module_2').bind('fadeIn',function(){
    initialize_jqgrid();
});

Is there a way I can make this work for all instances of $('#module_2').fadeIn(); without having to go to every instance and replace it with this?

$('#module_2').fadeIn().trigger('fadeIn');

The motivation behind this is just to have cleaner code, $('#module_2').fadeIn().trigger('fadeIn'); is a little redundant.

Thanks a lot!

4条回答
叼着烟拽天下
2楼-- · 2019-05-08 20:01

Sure,

var _old = $.fn.fadeIn;

$.fn.fadeIn = function(){
    var self = this;
    return _old.apply(this,arguments).promise().done(function(){
        self.trigger("fadeIn");
    });
};

// and your code: // replace .bind with .on if jQuery 1.7+
​$("div").bind("fadeIn",function(){alert("worky");});

$("div").fadeIn(2000);​​​​​​​​​​​​​​​​​

Demo
http://jsfiddle.net/gEVsX/2/

Update for comment

var _old = $.fn.fadeIn;

$.fn.fadeIn = function(){
    return _old.apply(this,arguments).trigger("fadeIn");
};

// and your code: // replace .bind with .on if jQuery 1.7+
​$("div").bind("fadeIn",function(){alert("worky");});

$("div").fadeIn(2000);​​​​​​​​​​​​​​​​​
查看更多
老娘就宠你
3楼-- · 2019-05-08 20:04

You could define your callback function and use it as a parameter to fadeIn().

function callback(){
    initialize_jqgrid();
}

$('div#module_2').fadeIn(duration,callback)
查看更多
4楼-- · 2019-05-08 20:08

Simple Function:

switch_module('div#module_1','div#module_2');


function switch_module(old_selector, new_selector){
    $(old_selector).hide();
    initialize_jqgrid();
    $(new_selector).fadeIn();
}
查看更多
Animai°情兽
5楼-- · 2019-05-08 20:10

You can use the callback function $('div#module_2').fadeIn(500, initialize_jqgrid);

and put everything in a function with generic selector call;

function fadeModule(selector)
{
    $(selector).fadeIn(500, initialize_jqgrid);
}

And call it like that fadeModule('div#module_2');

EDIT: 500 is the default duration for a fadeIn, put whatever you want.

查看更多
登录 后发表回答