2017-10-12 1 views
0

Ich bin neu in OOP in jQuery.OOP: jQuery Klassenmethode Aufruf auf Klick-Ereignis

Ich habe folgende Klasse

/* 
* 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); 

}; 

Jetzt habe ich mit folgendem Code meine Klasse auf einer Seite bin initialisiert.

Ich möchte addRemoveFavorite Methode aufrufen, wenn Klick Ereignis ausgelöst. Derzeit, wenn ich klicke, bekomme ich Fehler

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

Ich weiß nicht, wie Klassenmethode auf Click-Ereignis aufrufen. Ich habe gesucht, aber keine richtige Lösung bekommen.

Antwort

1

Dies ist nicht spezifisch für jQuery. Das Problem ist, dass Sie undefined als Ereignishandler übergeben, weil Sie addRemoveFavorite als eine lokale Variable definiert haben, nicht eine Eigentums- oder geerbte Eigenschaft. So this.addRemoveFavorite wird nicht gefunden, und undefined ist substituiert.

+0

Oh ja. das war mein Fehler. Danke @llama, um mich zu führen. – Dhara

+0

Gern geschehen. – llama

Verwandte Themen