用jquery事件更新javascript中的主类的正确方法是什么?
假设我有类似于:用jquery事件更新javascript中的主类的正确方法是什么?,javascript,Javascript,假设我有类似于: var MyApp = function() { this.name = "Stacy" } MyApp.prototype.updateName = function(newname) { this.name = newname; } MyApp.prototype.events = function() { $("#button").on("click", function(evt) { this.
var MyApp = function() {
this.name = "Stacy"
}
MyApp.prototype.updateName = function(newname) {
this.name = newname;
}
MyApp.prototype.events = function() {
$("#button").on("click", function(evt) {
this.name = "john"
});
}
在我的主页中,我有一个:
$(function () {
var instance = new MyApp();
})
我有一个按钮事件处理程序,可以更新名称:
$("#button").on("click", function(evt) {
// Update the name in MyApp to something else...
instance.name = "john" // I do not like using instance here, because it has to be "instance" has to be created before I can use it. I want to be able to make this independent of "instance" being created or not
});
正确的方法是什么,这样按钮处理程序将更新“MyApp”以获得正确的名称,而不显式地将创建的MyApp“实例”用作按钮单击处理程序的一部分
理想情况下,我希望将jquery事件处理程序放到“MyApp”中的某个位置,这样我就可以执行以下操作:
var MyApp = function() {
this.name = "Stacy"
}
MyApp.prototype.updateName = function(newname) {
this.name = newname;
}
MyApp.prototype.events = function() {
$("#button").on("click", function(evt) {
this.name = "john"
});
}
虽然它不起作用,因为它指的是其他东西
如何正确构造我的应用程序,使事件处理程序或多或少地更新“MyApp”的属性,使其独立于已创建的“实例”(即,我不再需要使用“实例”)?首先,如果创建setter函数,最好使用它!!:D
$("#button").on("click", function(evt) {
// Update the name in MyApp to something else...
//instance.name = "john"
instance.updateName("john");
});
然后,将事件处理程序放在对象MyApp的方法中是没有意义的,因为在您触发events()之前,它永远不会绑定onclick事件
然后我的组织方式是使用jQuery文档onload将所有DOM对象与应用程序的功能绑定在一起。通常是这样的:
MYAPP = {};
MYAPP.say_something = function () {
alert('lol, you clicked me!');
};
...
$(function () {
$('#my_button').click(MYAPP.say_something);
$('#other_element').mouseenter(MYAPP.another_method);
});
MYAPP.fetch_dom = function () {
return {
my_button: $('#my_button'),
other_element: $('#other_element')
};
};
对于需要处理大量元素的大型应用程序,如果为DOM元素提供名称空间,则可以更好地组织代码,如下所示:
MYAPP = {};
MYAPP.say_something = function () {
alert('lol, you clicked me!');
};
...
$(function () {
$('#my_button').click(MYAPP.say_something);
$('#other_element').mouseenter(MYAPP.another_method);
});
MYAPP.fetch_dom = function () {
return {
my_button: $('#my_button'),
other_element: $('#other_element')
};
};
你可以用一种非常简洁的方式来绑定事件
$(function () {
// first initiate DOM
my_dom = MYAPP.fetch_dom();
// Then bind events
my_dom.my_button.click(MYAPP.say_something);
my_dom.other_element.mouseenter(MYAPP.another_method);
});
这样,您就不必从程序的上千个点查找DOM中的特定元素,将硬编码id散布到任何地方,并对DOM结构执行无效的搜索
最后,在JS中使用文本比使用单词new要好得多。JS是一种典型的OOP语言,而new有点“违背自然”,这可能会让人感到痛苦。使用“new”的原因是,人们可以简单地包含my.JS文件,只需创建MyApp的“new”实例即可使用。你不必为singleton创建新实例。实际上,在任何情况下都不需要使用new(嗯……new Date())。只要加载MYAPP对象,就可以引用它。