2017-01-05 46 views
0

是否存在将这两个函数作为单个函数编写而不重复的简单明了的方法。我想我想以编程方式设置开/关方法。如何以编程方式附加和删除事件处理程序

function attachEventHandler(){ 
    $(document).on({ 
     ajaxStart: function() { 
     $("body").addClass("loading"); 
     }, 
     ajaxStop: function() { 
     $("body").removeClass("loading"); 
     } 
    }); 
} 

function removeEventHandler(){ 
    $(document).off({ 
     ajaxStart: function() { 
     $("body").addClass("loading"); 
     }, 
     ajaxStop: function() { 
     $("body").removeClass("loading"); 
     } 
    }); 
} 
+0

没有'.toggleEvent' – Justinas

+0

看看为关jQuery的文档:http://api.jquery.com/off/。您不需要添加函数实现,只需添加要删除处理程序的事件的名称即可。 – Tobi

+0

1)外面有决定标志。 2)删除逻辑。 3)如果标志开启,'on'内部会做些什么。在这里,我们并没有删除事件处理程序,而是保留事件处理程序并在需要时关闭逻辑。 –

回答

1

最简单回到我脑海里的答案是

var handlers = { 
     ajaxStart: function() { 
     $("body").addClass("loading"); 
     }, 
     ajaxStop: function() { 
     $("body").removeClass("loading"); 
     } 
    } 

function attachEventHandler(toggle){ 
    // here we are selecting the 'on' or 'off' 
    // property of the $(document) jquery element 
    // depending on whether the toggle is true or 
    // false. Because the 'on' and 'off' props are 
    // functions, we can call the property with 
    // `handlers` as the argument 
    $(document)[toggle ? 'on' : 'off'](handlers); 
} 

,并使用它,像这样:

attachEventHandler(true) // turn on 
attachEventHandler(false) // turn off 
+0

似乎工作一个治疗@lordvlad。谢谢。我可以在写“toggle === true”的地方写上“切换”吗? - wurz –

+0

是的,其实结果将是相同的 – lordvlad

0

可以使用。对()的函数绑定到多个事件:

$('#element').on('keyup keypress blur change', function(e) { 
// e.type is the type of event fired 
}); 

或者只是传递给函数作为参数传递给正常事件功能:

var myFunction = function() { 
... 
} 

$('#element') 
.keyup(myFunction) 
.keypress(myFunction) 
.blur(myFunction) 
.change(myFunction) 
+0

OPs的问题是在''off'' off''没有代码复制的情况下执行''''''''' –