event的名称空间

对于事件的名称空间,我们可以列举一个非常简单的例子。我们写一个名叫'clicked'的插件。它提供了两种方法:clicked 和unclicked。这个clicked方法给所有匹配的元素(当该元素被点击的时候)添加了一个“clicked”类名.unclicked方法就是移除"clicked"类名的。我们可以看下面的例子:

  1. ( function ($ ) {
  2.     $. fn. extend ( {
  3.         clicked : function ( ) {
  4.             return this. bind ( 'click' , function ( ) {
  5.                 $ ( this ). addClass ( 'clicked' );
  6.             } );
  7.         } ,
  8.         unclicked : function ( ) {
  9.             retun this. removeClass ( 'clicked' ). unbind ( 'click' );
  10.         }
  11.     } );
  12. } ) (jQuery );

我们可以使用这个插件
  1. $ ( 'div' ). clicked ( );

如果我们想停止使用这个插件的时候,我们可以调用unclicked()方法:

JavaScript:
  1. $ ( 'div' ). unclicked ( );
A Problem

But let's say I'm also using another plugin that attaches a click event to the same elements that the clicked plugin does. Calling unclicked would unbind all the click events, including those bound by your own code or another plugin.

但是问题出现了,当我也要在同一个元素中使用另外一个插件click事件的时候,我们调用unclicked方法将会解除所有的Click事件,包括在我们代码中或者在其他插件中绑定click事件。

出现这个问题,我们该怎么解决呢?我们可以通过名称空间解决这个问题:

名称空间提供了一个很简单的方法来区别事件处理函数。例如,一个插件可以给他的事件处理函数(仍然使用匿名函数处理函数)添加名称空间,这样我们就可以很容易的为他解除绑定。我们可以这样添加名称空间("type.namespace");

我们可以看下面的例子:

  1. ( function ($ ) {
  2.     $. fn. extend ( {
  3.         clicked : function ( ) {
  4.             return this. bind ( 'click.clicked' , function ( ) {
  5.                 $ ( this ). addClass ( 'clicked' );
  6.             } );
  7.         } ,
  8.         unclicked : function ( ) {
  9.             retun this. removeClass ( 'clicked' ). unbind ( 'click.clicked' );
  10.         }
  11.     } );
  12. } ) (jQuery );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值