开发者

Creating a jQuery plugin to cause individual elements to react when the window is resized. How do I handle the listeners?

开发者 https://www.devze.com 2023-02-07 08:36 出处:网络
I\'m working on a plugin that causes something to happen in selected elements when the window is resized. The logic on what happens is perfectly fine, but I\'m running into a conundrum when it comes t

I'm working on a plugin that causes something to happen in selected elements when the window is resized. The logic on what happens is perfectly fine, but I'm running into a conundrum when it comes to where to hook on the event listeners.

Basically, the code looks something like this:

$.fn.beAwesome = function() {
  return this.each(function(){
    // ???
  });
}

While I've completed the rest of the plugin (and have it working just fine on, say, a click even on this), I can't put it "all together" without solving this central issue.

I considered just adding an extra bind resize to $(window) for each awesome element, but there'd be no way to access the element from within the closure:

$.fn.beAwesome = function() {
  $window = $(window);
  return this.each(function(){
    $window.resize(function(){
      // can't access initial awesome element
    });
  });
}

The other solution that sprung to mind was to instantiate a global data store (probably in $(document).data('beAwesome') or something like that. This, however, doesn't seem开发者_运维百科 Javascript-like, blocking off access once the function runs its course, so I'd have to come up with some roundabout ways to do things like removing the hook. I've definitely seen approaches like these in Javascript libraries I've used in the past, but I don't know whether that's due to necessity or laziness on the authors' parts.

So is there an effective way to accomplish what I'm looking for?


You shouldn't bind to the resize event multiple times, will just end up with bloat and slowness.

What you could do is create a var to store all the elements that are to beAwesome. Bind to the resize event once. And then on resize do something will all the elements that are in the var.

(function($){ // closure to keep your pluggin contained.
    var elems = $([]);
    $(window).bind('resize.beAwesome', function(){
        if (!elems.length) return; //no need to continue if elems in empty.
        // Do something with elems here.
    });

    $.fn.beAwesome = function() {
      elems = elems.add(this);
      return this;
    }
})(jQuery);

You also might want to namespace your resize event.

0

精彩评论

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