简体   繁体   中英

jQuery “tagging” events

I'm not sure how to describe this, but I'll try with some basic code:

<input type="text" id="num" placeholder="eg: 55"/>

Let's say we add some basic filtering code:

$('.num').keyUp(function(){
    this.value = parseInt(this.value);
});

This is what the end-developer does. Now let's imagine the s/he also uses a form validation system of our design:

// ...
if(el.val()!=parseInt(el.val()))
    showError(el);
// ...

Let us presume our showError shows a tooltip only when the user hover over it:

function showError (el){
    el.css('border-color', 'red');
    el.mouseOver(function(){
        showErrorTooltip(this);
    });
}

That works fine, but what if the error has been fixed? With jQuery, you'd usually do:

removeError(el);

This function would remove some CSS stuff from the element in question, but, most importantly, it will also remove our mouseOver event like the one we added above:

function removeError(el){
    el.css('border-color': null); // default color
    el.unbind('mouseOver');
}

This works well until the end developer needs to do something flashy when the mouse hover over the element, by using jQuery's mouseOver.

The problem is, my removeError function clears both my event as well as the developer's event.

So, my final question is, how do I tag event callbacks so I can remove them selectively?


If the above didn't seem to make sense, this is some pseudo-code on what the result might look like:

Something like:

var tag_a = $('#a').click(function(){ alert('test1'); });
var tag_b = $('#a').click(function(){ alert('test2'); });
$('#a').unbind(tag_a);
$('#a').click(); // shows test2 only

The mechanism you're looking for is event namespacing: http://docs.jquery.com/Namespaced_Events

Example in your case:

el.bind('mouseOver.error', function() { ... })
el.unbind('mouseOver.error') //does not remove other mouse over events

我建议使用jQuery命名空间事件

You have to use a named function instead of an anonymous function

function showError (el){
  var onMouseOver = function(){
    showErrorTooltip(this);
  });
  el.css('border-color', 'red');
  el.bind('mouseOver', onMouseOver);
}

function removeError(el){
  el.css('border-color': null); // default color
  el.unbind('mouseOver', onMouseOver);
}

This will only unbind this function from mouseOver. The only problem is that the function onMouseOver has to be seen by removeError, since you dont show the whole code I am not able to tell you how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM