2017-10-12 11 views
0

我是jQuery中OOP的新手。OOP:點擊事件的jQuery類方法調用

我有下面的類

/* 
* myClass 
*/ 
var AlcoholOrder = function (options) { 

    /* 
    * Variables accessible 
    * in the class 
    */ 
    var vars = { 
     myVar: 'original Value' 
    }; 

    /* 
    * Can access this.method 
    * inside other methods using 
    * root.method() 
    */ 
    var root = this; 

    /* 
    * Constructor 
    */ 
    this.construct = function (options) { 
     $.extend(vars, options); 
    }; 

    var addRemoveFavorite = function(){ 
     alert('function called'); 
    }; 

    $(function() { 
     $(document.body).on('click', '.favorite-add', this.addRemoveFavorite); 
    }); 

    /* 
    * Pass options when class instantiated 
    */ 
    this.construct(options); 

}; 

現在我初始化我的類一個頁面下面的代碼。

$(document).ready(function($){ 
    var alcohol = new AlcoholOrder({ myVar : 'new Value' }); 
}); 

我想打電話addRemoveFavorite方法點擊事件發射。目前,當我點擊我得到錯誤

jquery-1.12.4.min.js:3 Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function

我不知道如何在點擊事件調用類的方法。我已經搜索,但沒有得到妥善解決。

回答

1

這不是特定於jQuery。問題在於您將undefined作爲事件處理程序傳遞,因爲您將addRemoveFavorite定義爲局部變量,而不是擁有的或繼承的屬性。因此找不到this.addRemoveFavorite,並且undefined被替換。

+0

哦,是的。那是我的錯誤。感謝@llama引導我。 – Dhara

+0

不客氣。 – llama