全局命名空间中事件的最佳实践

Best practices for events in global namespace?

本文关键字:最佳 事件 命名空间 全局      更新时间:2023-09-26

我还是JavaScript的新手,所以我认为我现在处理项目的方式在某种程度上影响了我思考如何在js中完成事情的方式。我已经明白,在js中编程时,最好使用模块。这让我开始思考js中的事件。例如,假设我有这个对象Monkey:

function Monkey(color, position){
   this.color = color;
   this.position = position;
   this.jumpAround = function() {
      /* jumps around and screams */
   };
}

假设我已经构建了一个完整的应用程序,包括monkeysgiraffesshih tzus,它们在网络应用程序中进行交互。那么应该如何处理这些事件呢?是否只需在全局命名空间中实现回调函数?类似:

//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标头中?也许这是一个愚蠢的问题,有一个显而易见的答案,但对我来说,似乎没有任何好的最佳实践

您可以将所有代码放入匿名自调用函数中,这也将创建闭包:

(function(){
    // create all your objects and define all events handlers here
})();

这样您的代码就不会污染全局命名空间,并且从外部无法访问。所有的事件处理程序都将在闭包中执行。

(注意:你也可以在jQuery库中找到它。在脚本文件的最后是暴露在外部世界的jQuery对象:window.jQuery = window.$ = jQuery;

我不完全确定我是否理解这个问题,但如果你的意思是处理由重复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
});

这里有一个关于对象继承的充实示例。http://jsfiddle.net/H4jqF/

CSS-只是一个基本的动物对象,具有0.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});