OOP:对click事件调用jQuery类方法

时间:2017-10-12 11:31:33

标签: javascript jquery oop

我是jQuery中的OOP新手。

我有以下课程

/*
 * 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未捕获的TypeError:   ((n.event.special [g.origType] || {})。handle || g.handler).apply不是   功能

我不知道如何在click事件上调用类方法。我已经搜索过但没有得到适当的解决方案。

1 个答案:

答案 0 :(得分:1)

这不是jQuery特有的。问题是您将undefined作为事件处理程序传递,因为您将addRemoveFavorite定义为局部变量,而不是拥有或继承的属性。因此找不到this.addRemoveFavoriteundefined被替换。