2012-03-07 34 views
1

我想弄清楚這是否可能。首先,我應該說我正在克隆FileReader對象,並在整個應用程序中保留該對象(這樣我可以允許用戶在正式上傳文件之前刪除它們)。刪除另一個函數內的對象

所有的工作正常,但我掛了,試圖找出允許用戶從這個克隆的對象中刪除成員的最佳方式(成員是相同的文件[在我的情況的圖像]這將是在正常的FileReader對象中找到)。

所以基本上我已經克隆了對象,添加了一個pseudoHash它允許我引用用戶想要刪除的克隆成員,並且在單擊「刪除」圖標時,我搜索關聯的pseudoHash我已經綁定了該圖標,在克隆的對象中,並刪除該成員。如果對象是在它自己的函數中,這將工作得很好,但事實並非如此。所以我無法刪除對象的成員。在這種情況下,我在全球範圍內製作了files,但它仍然無法正常工作。

 // Our FileList object 
     files = e.target.files; 
     // Create a clone since FileList is readonly 
     files = cloneObject(files); 
     // If files isn't empty, give the user the option to remove members 
     if (files.length) { 
      files = removeSelected(files); 
     } 

這是我的功能。不幸的是,當我點擊從「上傳隊列」中刪除一個圖像時,它應該經過這個函數,但它實際上不會刪除該對象,因爲我知道Javascript並沒有完全刪除對象,所以如果它是最後一個成員,我嘗試將其設置爲空對象,但這不起作用。如果它不是最後一個成員,我只想在它的位置刪除它。再次,因爲這是在一個單獨的函數中,而不是父代,它只是刪除對變量的本地引用。

// Remove selected file from cloned fileList object 
    var removeSelected = function(files) { 
    var dataPseudoHash = $(this).attr('data-pseudo-hash'); 

     $('#js-selected-files').delegate('.js-remove-selected', 'click', function() { 

      if (files.length == 1) { 
       $('.js-image-upload').attr('disabled', true).addClass('btn_disabled'); 
       files = {}; 
       delete files; 
      } else { 
       // Loop through our files object and if we find a member with the same 
       // pseudoHash as the attribute from whatever 'X' icon that was clicked, remove it 
       $.each(files, function(i, dataPseudoHash) { 
        if (files[i].pseudoHash == dataPseudoHash) { 
         delete files[i]; 
         files.length -= 1; 
        } 
       }); 
      } 

      // Remove hidden input that prevents duplicate files being uploaded of 
      $('.js-pseudo-hash[value="' + dataPseudoHash + '"]').remove(); 

      $(this).parent().fadeOut('normal', function() { 
       $(this).remove(); 
      }); 
     return files; 
    }; 

什麼是最好的處理方法?也許將標誌設置爲true或false,然後根據情況在父功能中相應地刪除對象或其成員?不太確定。除此之外,我已經上傳了文件,但我需要找出如何刪除對象或對象的屬性(如果單擊所有「刪除」圖標)。

回答

0

首先,你應該知道delete操作符只刪除一個數組或元素的一個元素,而不是整個數組。在你的第一個,如果條件

if (files.length == 1) { 
      $('.js-image-upload').attr('disabled', true).addClass('btn_disabled'); 
      files = {}; 
      delete files; 
} 

您刪除整個對象,返回false。 現在,如果您可以在任何情況下手動檢查第二個條件是否爲真,會更好。

相關問題