简体   繁体   中英

How can I unbind (off) listening to a DOM element without effecting others listening to same event?

I have this code:

 $('#el').change(function (e) {
     if (!self.m_selected)
         return;
     self._onChange(e);
 });

That is in multiple places (multiple instances of objects)... and in some cases I would like a single instance to stop listening to change event, BUT, other instances still need to listen.

If I just run $('#el').off('change'); , all will stop listening, but I only want this one class instance to stop listening?

If you save a reference to the handler function, you can remove just that one particular handler:

var handler = function (e) {
        if (!self.m_selected)
            return;
        self._onChange(e);
    };
$('#el').change( handler );

And later:

$("#el").off('change', handler);

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