简体   繁体   English

事件取决于jQuery上的动态变量

[英]Events depending on a dynamic variable at jQuery

I'm wondering which would be the proper way to deal with events which depend on the status of a variable. 我想知道哪种方法是处理依赖于变量状态的事件的正确方法。

Right now, I have a listener which it is only added if the option isTablet is set to true. 现在,我有一个仅在选项isTablet设置为true时添加的侦听器。 (as if not, it breaks in old versions of IE). (好像没有,它会在IE的旧版本中损坏)。 So it looks like this: 所以看起来像这样:

if(options.isTablet){
    document.addEventListener('touchmove', function(e){
      ....
    });
}

Now, I'm having troubles if I want to change the variable isTablet dynamically with a setter and It won't load the event touchmove . 现在,如果要用设置器动态更改变量isTablet ,会遇到麻烦,并且不会加载touchmove事件。

$.fn.myPlugin.setIsTablet = function(value){
    options.isTablet = value;
}

I guess the simple way is always adding the event and inside it deciding whether or not to execute the code: 我猜最简单的方法是始终添加事件并在事件内部确定是否执行代码:

document.addEventListener('touchmove', function(e){
    if(options.isTablet){
        ....
    }
});

But throws an error in IE 8: 但是在IE 8中引发错误:

Object doesn't support property or method 'addEventListener' 对象不支持属性或方法“ addEventListener”

What would be the way of doing it? 这样做的方式是什么? Thanks. 谢谢。

Generally, I would always add the listener and check the condition inside. 通常,我总是会添加侦听器并检查其中的条件。 To avoid your error, since you're using jQuery, just use jQuery: 为避免错误,由于使用的是jQuery,只需使用jQuery:

$(document).on('touchmove', function(e){
    if(options.isTablet){
        ....
    }
});

If you have a handler that is called very often, you could consider turning it off when not needed. 如果您有一个经常调用的处理程序,则可以考虑在不需要时将其关闭。 Something like this: 像这样:

function myHandler(e) { ... }

$.fn.myPlugin.setIsTablet = function(value){
    options.isTablet = value;
    if (value) {
        $(document).off('touchmove').on('touchmove', myHandler);
    } else {
        $(document).off('touchmove');
    }
}

Be careful not to bind the handler more than once (like if true is sent to setIsTablet more than once in a row). 注意不要多次绑定处理程序(例如,如果true setIsTablet多次发送给setIsTablet )。 You could also use a flag instead of unbinding/binding like I've shown. 您也可以使用标志而不是像我所示的那样取消绑定/绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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