2014-01-24 23 views
0

我試圖刪除一個特定的ember formset。通常在我的控制器中,這受到控制器的影響,但在jquery腳本之後這個=「p」aragraph。Jquery在Ember中弄亂了「this」

模板

<p {{bind-attr class=id}}{{action 'getId'}}> Delete</p> 

的Javascript

getId: function(){ 
     $("p").on('click',function() { 
     var Id = $(this).attr('class'); 
     console.log(Id); // Returns id properly . 
     // here this reffers to "p" normally it reffers to the controller. 
     }); 
     this.deleteSpecificFormset(Id); // "Id" is now undefined 
     }, 

    deleteSpecificFormset: function(formCounterID){ 
     var oldPersonFormCount = this.get('personFormCount'); // This as json containing e.g {id:1} 
     var newFormCounter = oldPersonFormCount[formCounterID -1].delete; 
     this.set('personFormCount', newFormCounter); 
    }, 

可以OFC報價燼相關版本與

歡呼聲,

克里斯蒂安

+0

因爲你是在p'的'上下文有這麼'$(這個)'屬於'p'那裏,你怎麼能說這通常是指控制器? – Jai

+0

那麼通常我不jquery,所以通常它是由這個 –

+0

調用的控制器當然''你的this.deleteSpecificFormset'行上的'Id'是未定義的。你爲什麼會這麼想?它只在點擊回調中定義,並且該特定的行*不在點擊回調中。 'context'之外的 – Tomalak

回答

1

它看起來像一個功能範圍問題。嘗試在外部函數中定義Id,稍後在相同的上下文中可用。

getId: function(){ 
     var Id; //declare the variable outside of the context of the jQuery anonymous function scope 
     $("p").on('click',function() { 
     Id = $(this).attr('class'); 
     console.log(Id); // Returns id properly . 
     // here this reffers to "p" normally it reffers to the controller. 
     )}; 
     this.deleteSpecificFormset(Id); // "Id" should now be defined 
} 

或者,你可以在一個self變量固定外範圍this參考,並從回調內部調用deleteSpecificFormset

getId: function(){ 
      var self = this; 
      $("p").on('click',function() { 
      var Id = $(this).attr('class'); 
      self.deleteSpecificFormset(Id); 
      )}; 

    } 
+0

我想你想提一下。 – Jai

+0

是的,謝謝。補充說明。 – max

+0

謝謝(是)這工作:) –