在JavaScript对象内部或外部设置事件更好吗?
在JavaScript对象内部或外部设置事件更好吗 例如,下面是一些简单的代码,用于生成在页面底部弹出的工具栏(我在这里使用jQuery): 在上面我有工具栏对象之外的事件。这更好还是这样:在JavaScript对象内部或外部设置事件更好吗?,javascript,jquery,oop,Javascript,Jquery,Oop,在JavaScript对象内部或外部设置事件更好吗 例如,下面是一些简单的代码,用于生成在页面底部弹出的工具栏(我在这里使用jQuery): 在上面我有工具栏对象之外的事件。这更好还是这样: tool_bar = { show : function() { window.onload = function() { $('#bottomBox') .show() .animate({ 'bottom' : '0' }, 700)
tool_bar = {
show : function() {
window.onload = function() {
$('#bottomBox')
.show()
.animate({ 'bottom' : '0' }, 700)
;
};
},
close : function() {
$('#bottomBox span').click(function() {
$('#bottomBox').hide();
});
}
};
$(function() {
tool_bar.close();
});
tool_bar.show();
应该提到的是,两者都有效。我只想知道什么被认为是更好的练习。我只想做:
$(function() {
var bottom = $('#bottomBox')
.show()
.animate({
'bottom': '0'
}, 700);
$('span', bottom).click(function() {
bottom.hide();
});
});
你也可以把它做成一个插件:
$.fn.toolbar = function(){
this
.show()
.animate({
'bottom': '0'
}, 700);
$('span', this).click(function() {
$(this).parent().hide();
});
return this;
}
$(function() {
$('#bottomBox').toolbar();
}
那些你已经声明或内置的东西——其实并不重要,你在哪里重新定义它的价值 在您的情况下,两个代码的结果将是相同的。 唯一的区别是当您声明时:
var x=“x”
在函数或if或任何运算符之外-它将成为全局变量并立即赋值。
您还可以声明一个空的varvar x将>编码为全局变量,并通过函数或任何运算符分配一个值,该值将保持不变。
由于window.onload
是一个全局对象的事件-这无关紧要,您在哪里给它赋值。我赞成将机制和策略分离,因此在您的示例中,我将以第一种方式构造代码
第二种方法也不错,我只是a)调用不同的函数,比如showOnLoad()
,b)使用适当的事件注册(Guffa的答案可能是注册“加载”事件的最佳方法),而不是分配给窗口。onload
我认为封装是一个值得追求的目标。这意味着您将对象的行为封装在该对象中。外部世界应该能够控制对象的安装或删除,并且能够控制客户端可能想要的任何其他行为,但是“在”对象内的行为应该完全在对象内实现(至少对于默认行为)
在您的特定情况下,我认为您应该允许外部代理安装或删除工具栏,但工具栏安装后的操作应由工具栏本身处理
我建议这样的实现具有以下优点:
- 所有行为都封装在对象中
- 由于id传递给构造函数,因此可以有多个id
- 对象负责管理自己的事件处理程序,外部世界不必知道这一点
- 它有用于
show()
和hide()
的外部可用方法
- 您可以轻松添加其他行为
您可以实现如下工具栏:
var bottomToolbar = new tool_bar("bottomBox", true);
下面是对象的代码:
// id is a required argument
// show is an optional argument (true means to show it as soon as possible)
var tool_bar = function(id, show) {
this.id = '#' + id;
this.show = function() {
$(this.id).show().animate({ 'bottom' : '0' }, 700);
};
this.hide = function() {
$(this.id).hide();
};
// .ready() code will either be fired immediately if document already ready
// or later when document is ready, so the code can be used either way
$(document).ready(function() {
if (show) {
this.show();
}
$(this.id + " span").click(function() {
this.hide();
});
});
}
似乎OP有一个show()
方法是有充分理由的。在它被隐藏之后,能够再次展示它会很好。您的实现不再具有show()
方法。@jfriend00:似乎不是这样。问题中的第二个实现没有这样的show方法。好的,但是第一个实现有。
// id is a required argument
// show is an optional argument (true means to show it as soon as possible)
var tool_bar = function(id, show) {
this.id = '#' + id;
this.show = function() {
$(this.id).show().animate({ 'bottom' : '0' }, 700);
};
this.hide = function() {
$(this.id).hide();
};
// .ready() code will either be fired immediately if document already ready
// or later when document is ready, so the code can be used either way
$(document).ready(function() {
if (show) {
this.show();
}
$(this.id + " span").click(function() {
this.hide();
});
});
}