2013-11-22 46 views
0

我通過JQuery回調調用remove。元素fadeOut成功,但刪除似乎沒有被調用,因爲在fa​​deOut調用後this._id無法訪問?如何刪除元素的淡入淡出之後?

請參閱下面代碼中的註釋。

'click .destroy' : function(){ 
      console.log(this._id); //This is fine. 
    $("#"+this._id).fadeOut('slow',function() { 
      console.log(this._id); //This returns undefined! 
      Links.remove({_id:temp}); //Thus this does not work... 
    }); 
} 

然而,當我試圖讓this._id變量的副本,然後通過Links.remove(temp);刪除,我得到:Not permitted. Untrusted code may only update documents by ID.」 Meteor error因爲這是客戶端代碼。

不安全的軟件包已打開。

我該如何着手解決這個問題?

回答

2

fadeOut回調的回調範圍與點擊處理程序的回調範圍不同。 this與您認爲的價值不同。我建議存儲先前範圍的this在一個變量:

'click .destroy' : function(){ 
    var that = this; 
    console.log(that._id); 
    $("#"+this._id).fadeOut('slow',function() { 
    console.log(that._id); 
    }); 
} 

另外,從客戶端代碼,默認情況下,不允許修改的集合。 It's explained below the sample code for remove。順便說一句,「不可信代碼」可以被認爲是「客戶端代碼」。

這是不是:

  • 你這樣做的服務器端,所以你可以做一些驗證和認證。更安全。
  • 或者只是簡單地允許在收集的修改做collection.allow
2

不是使用var that = this黑客,只是存儲在外部封閉的ID:

'click .destroy' : function(){ 
    var id = this._id 
    $("#"+id).fadeOut('slow',function() { 
     console.log(id); 
    }); 
} 

我通常查看/自黑客作爲最後的手段;大多數情況下,您可以在外部封閉中存儲一個或兩個變量,並且它會更乾淨。