Pra*_*een 2 javascript jquery event-handling javascript-events
我在Javascript代码中编写了2个函数,如下所示
Manager = FormManager.extend({
First: function () {
var response = this.Second("Feature"); //I'm able to get the alert
//I have added a click event handler
$('#element').on('click', function(){
var newResponse = this.Second("Bug"); //The alert is not poping
});
}
Second: function (type) {
alert(type);
//Performs certain operation
}
});
Run Code Online (Sandbox Code Playgroud)
错误:未捕获TypeError:对象#没有方法'秒'
我也尝试过不使用this关键字
Second("Bug") // Error: There is no method
Run Code Online (Sandbox Code Playgroud)
虽然这是我正在玩的程序的简化格式(按顺序显示一个简单的例子).我正在努力找出原因.
有人可以指引我走正确的道路吗?
你使用不正确this.试试这种方式.this处理程序内部不代表#element函数本身的上下文.
var self = this; //cache the context here
$('#element').on('click', function(){
var newResponse = self.Second("Bug"); //Access it with self
});
Run Code Online (Sandbox Code Playgroud)
此外,我认为你在First功能定义之后和Second功能之前缺少一个逗号.
您给出的回调的原因是从元素的上下文中调用,以便您的this上下文发生更改.thiscontext指的是调用回调的上下文.但是还有其他方法可以解决这个问题,例如使用$ .proxy,同时使用ecmaScript5 Function.prototype.bind将回调绑定到jquery,但理想情况下你不想这样做,因为大多数情况下你需要上下文处理程序内部的元素.