Monkey
function Monkey(color, position){
this.color = color;
this.position = position;
this.jumpAround = function() {
/* jumps around and screams */
};
}
并说我已经使用monkeys
,giraffes
和shih tzus
构建了一个完整的应用程序,可以在webapp中进行交互。那么事件应该如何处理呢?您是否只是在全局命名空间中实施回调函数?像:
//objects
var monkey = new Monkey(brown, pos);
var giraffe = new Giraffe(yellow, pos);
var shih_tzu = new Shih_tzu(white, pos);
//event handlers
this_and_that.onclick = function() { /* this and that happens */ }
...
然后在html标题中包含此文件?也许这是一个愚蠢的问题,有一个明显的答案,但仍然是我似乎没有任何好的最佳实践 ......
答案 0 :(得分:1)
我不完全确定我理解这个问题,但如果你的意思是处理由重复elem.onclick = function() {}
引起的javascript事件的覆盖,我会使用这个函数:
function addEvent(obj,event,func)
{
if(typeof func !== 'function')
{
return false;
}
if(typeof obj.addEventListener == 'function' || typeof obj.addEventListener == 'object')
{
return obj.addEventListener(event.replace(/^on/,''), func, false);
}
else if(typeof obj.attachEvent == 'function' || typeof obj.attachEvent == 'object')
{
return obj.attachEvent(event,func);
}
}
addEvent(this_and_that,'onclick',function(e) {
//do stuff
});
答案 1 :(得分:1)
您可以将所有代码放在anonymous self-invoking function内,这也会创建closure:
(function(){
// create all your objects and define all events handlers here
})();
然后您的代码将不会污染全局命名空间,并且无法从外部访问。所有事件处理程序都将在闭包内执行。
(一方面注意:你也可以在jQuery库中找到它。在脚本文件的最后是暴露给外部世界的jQuery对象:window.jQuery = window.$ = jQuery;
)
答案 2 :(得分:1)
这是一个带有对象继承的充实示例。 http://jsfiddle.net/H4jqF/
CSS - 只是一个基础动物对象,具有.5秒平滑过渡,用于属性更改时(例如,使我们的动物JUMP)。
.animal {
position: absolute;
transition: all 0.5s ease;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
}
JavaScript
// simple HTML animal - parent class
function Animal(color, position) {
this.color = color;
this.position = position;
this.elm = document.createElement("IMG");
this.elm.className = "animal";
this.elm.style.backgroundColor = this.color;
this.update = function() {
// update the the HTML element
this.elm.style.left = this.position.x + "px";
this.elm.style.top = this.position.y + "px";
};
this.jump = function(height) {
// cheesy jump animation
// we'll use a CSS transition to smooth it out
this.position.y -= height;
this.update();
// hard code it to come back down in 500ms
// .bind(this) is used to scope the function to this instance
window.setTimeout(function() {
this.position.y += height;
this.update();
}.bind(this), 500);
};
this.update();
}
// our subclass Dog
function Dog(color, position) {
// inherit all of the parent objects properties and methods
Animal.apply(this, arguments);
// finish setup of the element
this.elm.src = "dog.png";
document.body.appendChild(this.elm);
// add our onclick event that will fire jump
this.elm.onclick = function() {
this.jump(100);
}.bind(this);
}
// spawn some dogs
new Dog("red", {x: 50, y: 200});
new Dog("blue", {x: 200, y: 200});