开发者

how to reuse effect instance on jquery

On mootools I'm used to declare once and reuse often. A开发者_开发知识库n FX example would go like this:

myEffect1 = new Fx.Slide($('myElement1'));

How should I go on jQuery? Meaning, the docs make it straightfoward to use:

$('myElement1').click(function(e){
    this.slideToggle();
});

But if I want to call this effect somewhere else on my code will I have to re-declare it? And isn't this approach more resource hungry than the one above? How would this be properly done on jQuery?


Just manually cache the result set in a variable before calling the function, then reuse the function as needed:

var $el_one = $("#path .to > .selection"), // Stores jQuery object
    $el_two = $("#path .to > .second");    // Stores jQuery object

var effect = function(){
    $el_one.fadeIn();
    $el_two.fadeOut();
}

Now you can call effect any time without reselecting the items. They instead use the cached jQuery selection to animate correctly.

If you need more clarity, let me know.


var slideToggleEffect = function(e){
    this.slideToggle();
};

$('myElement1').click(slideToggleEffect);
$('myElement2').click(slideToggleEffect);
...


I'd go with a plugin in this case. For example here's a plugin that I use often - a very simple slide and fade toggle effect.

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({opacity: 'toggle', height: 'toggle'}, "fast", easing, callback);
};

Now you can call slideFadeToggle on any selector like this:

$("#somedom").slideFadeToggle();


Since every command acts on a jQuery object (the object returned by calling $() on a selector), the example you've given is the nearest comparison to what you're used to in MooTools, as far as I can see.

Is it more resource hungry? Well, that's a complex question to answer as instantiating objects is only one piece of client side code. Some framework methods for performing certain operations are better in some situations and worse in others.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜