[英]OOP : jQuery class method call on click event
I am new to OOP in jQuery. 我是jQuery OOP的新手。
I have following 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);
};
Now I am initialising my class in one page with following code. 现在,我使用以下代码在一页中初始化我的课程。
$(document).ready(function($){
var alcohol = new AlcoholOrder({ myVar : 'new Value' });
});
I want to call addRemoveFavorite
method when click event fired. 点击事件触发时,我想调用
addRemoveFavorite
方法。 Currently when I click I am getting error 目前,当我单击时出现错误
jquery-1.12.4.min.js:3 Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function
jquery-1.12.4.min.js:3 Uncaught TypeError:((n.event.special [g.origType] || {})。handle || g.handler).apply不是一个函数
I don't know how to call class method on click event. 我不知道如何在点击事件上调用类方法。 I have searched but not getting proper solution.
我已经搜索过但没有找到合适的解决方案。
This isn't specific to jQuery. 这并非特定于jQuery。 The trouble is that you're passing
undefined
as the event handler, because you defined addRemoveFavorite
as a local variable, not an owned or inherited property. 问题在于您将
undefined
传递为事件处理程序,因为您将addRemoveFavorite
定义为局部变量,而不是拥有或继承的属性。 So this.addRemoveFavorite
is not found, and undefined
is substituted. 因此找不到
this.addRemoveFavorite
,并且将undefined
替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.