开发者

Using jQuery binds for "everything"?

开发者 https://www.devze.com 2023-03-10 23:23 出处:网络
I\'ve been falling in love with jQuery bind. The reason is that it grants me easy access to the event - and a uniform way to make functionality accessible. Here are examples:

I've been falling in love with jQuery bind. The reason is that it grants me easy access to the event - and a uniform way to make functionality accessible. Here are examples:

$menu = $('<span id="menuid"></span>');

$menu.bind('populate', function() {
    // put stuff in the menu
}

$menu.trigger('populate');

Which is exactly the same as this:

$menu = $('<span id="menuid"></span>');

var _populateMenu = function() {
    // put stuff in the menu
}

_populateMenu();

But I can string all the binds together, and also - as said earlier - do the same for 'populate', 'place', 'hide', 'show' etc. I've written rather large jQuery plugins with nothing but binds - and profiled it for speed and calls. The bind method uses marginally more tim开发者_如何学Goe and calls than the "normal" way.

An added benefit from this is that I can easily just trigger stuff from anywhere. Like this:

$("#" + menuid).trigger('placement');

While if I want access to the functions in the jQuery-plugin, I'd need to assign it to a variable to do so.

So - is there really anything in the way of doing it this way? Or should I keep functions as functions and only bind on actual events (like show, hide, keyup etc)? I just find this stuff extremely powerful. But I fear that it has a cost that I'm not seeing.


The advantage of doing things that way is that it decouples your independent blocks of code, and makes it possible to trigger behavior without the code having to even know if such behavior is present on a particular page.

There's a cost, as you say, but depending on your application it may be worth it. If the code needs to invoke functionality thousands and thousands of time per "keypress" event, then probably it's a bad idea. But a dozen or two function calls vs. event triggers really isn't going to add up to much time in modern browsers.

I would also say that when the functionality in question has nothing to do with the DOM, then using the jQuery event system would be a fairly weird anti-pattern, and I'd avoid that.

0

精彩评论

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

关注公众号