javascript - 面向对象 : jQuery class method call on click event

标签 javascript jquery oop

我是 jQuery 中的 OOP 新手。

我有以下类(class)

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

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

最佳答案

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

关于javascript - 面向对象 : jQuery class method call on click event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46708493/

相关文章:

面向对象设计: where to put responsability?

javascript - 使用 Jquery 选择具有后缀 id 和类名的元素

javascript - 当 method=get 且 URL 包含散列时,使用 Javascript 更改表单操作时 IE 中的错误

javascript - jquery 单击无法正常工作

javascript - CSS 径向计数器 - 添加另一个圆圈来填充缺失的部分

oop - 类设计(UML类图)

oop - Smalltalk:消息的发送者是什么?

javascript - 将此信息存储在数组或数据库中更好吗?

jquery - JSON Post 调用错误函数

javascript - 使用javascript根据屏幕大小动态调整文本框的宽度