我有一个简单的jQuery ready事件,它通过调用setupView对象中的a函数来初始化视图。
我的问题是,从如下所示的init函数中调用函数setSomethingImportant的合适方式是什么?
由于调用是在与init函数不同的执行上下文中进行的,因此this.setSomethingImportant()不起作用。但是,如果我使用setupView.setSomethingImportant(),它就能正常工作。我遇到的问题是,如果变量名称(setupView)发生更改,我也必须更改代码体。
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant();
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);发布于 2012-08-10 00:09:32
将this存储到变量中:
var setupView = {
currentState: "CT",
init: function() {
// Keep a reference to 'this'
var self = this;
$("#externalProtocol").change(function() {
console.log("Changed =" + $(this).val());
// Use the old 'this'
self.setSomethingImportant();
});
},
setSomethingImportant: function() {
this.currentState = "TC";
console.log("Something has changed :" + this.currentState);
}
};请参阅。
发布于 2012-08-10 00:09:31
只需单独声明函数,然后像这样调用:
function setSomethingImportant(context) {
context.currentState="TC";
console.log("Something has changed :" + context.currentState );
};
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant(this);
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
setSomethingImportant(this);
}
}
}(jQuery);发布于 2012-08-10 00:11:35
请注意,我更改了原始解决方案。我现在使用even.data将数据传递给事件处理程序。
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change({ _this: this }, function (event) {
console.log("Changed =" + $(this).val());
event.data._this.setSomethingImportant();
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);https://stackoverflow.com/questions/11887378
复制相似问题