[英]A simple JS code and I am receiving the same result over and over again, I think, I may have done a logical error,
[英]Am I binding events over and over again in this jQuery code?
因此,我使用了一個非常出色的工具Visual Event ,它顯示了綁定到對象的所有事件處理程序-我注意到每次單擊或玩弄對象並檢查綁定到該對象的事件處理程序列表時,都會看到每次都更多。 我的問題是這個:用console.trace或stack trace來固定javascript錯誤的源頭? 在使用Visual Event和其他人的建議之后,我在想我的問題是我可能一次又一次地將相同的處理程序綁定到相同的事件。 有沒有辦法定期取消綁定?
我的應用程序有許多插件可以連接到動態創建的div
。 這些divs
可以調整大小並在該位置移動。 該應用程序是一種編輯器,因此用戶可以按照自己喜歡的任何設計來排列這些div(包含圖像或文本)。 如果用戶單擊div,則它會變為“已激活”,而頁面上的所有其他div都將變為“已停用”。 我有一大堆相關的插件,像activateTextBox
, initTextBox
, deactivateTextBox
, readyTextBox
,等等。 每當首次創建div時,都會在創建后的第一次調用一次init
插件,如下所示:
$(mydiv).initTextBox();
但readyTextBox
和activateTextBox
和deactivateTextBox
通常被稱為,這取決於其他用戶的事件。
在init
,我首先使用諸如resizable()
和draggable()
類的綁定對象,然后將框“准備好”使用
$.fn.extend({
initTextBox: function(){
return this.each(function() {
// lots of code that's irrelevant to this question
$this.mouseenter(function(){
if(!$this.hasClass('activated'))
$this.readyTextBox();
}
$this.mouseleave(function(){
if($this.hasClass('ready')){
$this.deactivateTextBox();
$this.click(function(e){
e.preventDefault();
});
}
});
});
});
這是readyTextBox
插件的簡化摘要版本:
(function($){
$.fn.extend({
readyTextBox: function(){
return this.each(function() {
// lots of code that's irrelevant to this question
$this.resizable({ handles: 'all', alsoResize: img_id});
$this.draggable('enable');
$this.on( "dragstop", function( event, ui )
{/* some function */ });
$this.on("resizestop", function( event, ui ){ /* another function */ });
// and so on
});
然后是activateTextBox()
:
$.fn.extend({
activateTextBox: function(){
return this.each(function() {
// lots of code that's irrelevant to this question
$this.resizable('option','disabled',true); //switch of resize & drag
$this.draggable('option', 'disabled', true);
});
然后deactivate
,使用以下代碼再次啟用可拖動和可調整大小的代碼:
$this.draggable('enable'); $this.resizable('option','disabled',false);
這些div或“文本框”包含在一個名為content
的較大div中,這是我在content
擁有的點擊代碼:
$content.click(function(e){
//some irrelevant code
if( /* condition to decide if a textbox is clicked */)
{ $(".textbox").each(function(){ //deactivate all except this
if($(this).attr('id') != $eparent.attr('id'))
$(this).deactivateTextBox();
});
// now activate this particular textbox
$eparent.activateTextBox();
}
});
這幾乎是與文本框相關的代碼。 為什么每次我拖動一些東西然后檢查Visual Event時,點擊,拖動和鼠標懸停都比以前更多? 同樣,用戶與頁面的互動越多,事件花費的時間就越長。 例如,我從一個div鼠標移出,但move
光標花費過長...時間回到默認值。 我退出了拖動,但是在准備好接受更多用戶點擊之前,一切都停滯了一段時間。因此,我猜問題是我將太多東西綁定到同一事件上,需要在某些時候解綁定點? 它變得如此糟糕,以至於可拖動最終在某些時候停止工作。 文本框只是卡住了-它們仍然可以調整大小,但是拖動停止工作。
我是否一再約束事件
是。 看一下你的代碼:
$this.mouseenter(function(){
…
$this.mouseleave(function(){
…
$this.click(function(e){
…
});
});
});
這意味着每次將鼠標懸停在元素上時,都會添加另一個離開處理程序。 當您離開該元素時,所有這些處理程序都會添加另一個click事件。
我不確定您要做什么,但是有幾種選擇:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.