2012-09-04 57 views
2

有兩個綁定到$(window).scroll()的js腳本。在一個腳本(example1.js)中,當滿足某些條件時,我需要解除綁定事件(或找到可接受的替代方案),但這會導致事件完全解除綁定,並刪除所有功能。解除綁定多次的事件

我想要做的是,一旦符合標準,停止滾動事件從example1.js的發射而不是example2.js。

example1.js

function exampleFunction(self) { 
    $(window).scroll(function() { 
     if ($(window).scrollTop() >= $(document).height() - $(window).height() - 364) { 
      self.start(); 
     } 
    }); 

    $.ajax({ 
     url: self.settings.dataUrl, 
     dataType: "json", 
     async: false, 
     cache: false, 
     success: function (json) { 
      if (json.data.length) { 
       self.json = json; 
       self.addImages(); 
      } else { 
       $(window).unbind('scroll'); 
      } 
     } 
    }); 
} 

example2.js

$(window).scroll(function() { 
    someFunction(); 
}); 

回答

2

看看Namespaced Events。這將允許您命名空間事件,然後僅解除綁定該名稱空間,使其他綁定保持不變。

例如:

// Create Bindings // 
$(window).bind('scroll.example1', function(e){ 
    ... 
}); 

$(window).bind('scroll.example2', function(e){ 
    ... 
}); 

// Unbind ONLY .example1 Namespace // 
$(window).unbind('scroll.example1'); 

我希望這有助於!

+0

非常好,正是我所需要的。謝謝! – bflemi3

+0

@ bflemi3太好了!很高興我能幫上忙。 – dSquared

1

綁定事件時使用namespaced事件。

例子:

//bind click.a 
$('.class').on('click.a', function(){ alert ('inside a space'); }); 
//bind click.b 
$('.class').on('click.b', function(){ alert ('inside b space'); }); 

//unbind click.b 
$('.class').off('click.b'); 

//trigger click.a 
$('.class').trigger('click.a'); 

在你的情況,

example1.js

function exampleFunction(self) { 
    $(window).on('scroll.e1', function() { //bind scroll.e1 
     if ($(window).scrollTop() >= $(document).height() - $(window).height() - 364) { 
      self.start(); 
     } 
    }); 

    $.ajax({ 
     url: self.settings.dataUrl, 
     dataType: "json", 
     async: false, 
     cache: false, 
     success: function (json) { 
      if (json.data.length) { 
       self.json = json; 
       self.addImages(); 
      } else { 
       $(window).unbind('scroll.e1'); //unbind scroll.e1 
      } 
     } 
    }); 
} 

example2.js

$(window).on('scroll.e2', function() { //bind scroll.e2 
    someFunction(); 
});