【问题标题】:Best practices for events in global namespace? [duplicate]全局命名空间中事件的最佳实践? [复制]
【发布时间】:2013-08-05 15:30:02
【问题描述】:

我会说,我仍然是 javascript 的新手,所以我认为我现在从事项目的方式正在塑造我思考应该如何在 js 中完成事情的方式。我知道在 js 中编程时最好使用模块。这让我想到了 js 中的事件......例如说我有这个对象Monkey

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

假设我已经构建了一个像这样的完整应用程序,带有monkeysgiraffesshih tzus,它们在 web 应用程序中交互。那么事件应该如何处理呢?您是否只需要在 全局命名空间 中实现 callbackfunctions?喜欢:

//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 标头中?也许这是一个有明显答案的愚蠢问题,但我仍然觉得好像没有任何好的最佳实践...

【问题讨论】:

标签: javascript javascript-events


【解决方案1】:

您可以将所有代码放入anonymous self-invoking function,这也会创建closure

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 那么您认为这是在 javascript 中使用事件处理程序的最佳实践吗?或者只是一种不使全局命名空间混乱的方法?
    【解决方案3】:

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

    CSS - 只是一个基础动物对象,具有 0.5 秒的平滑过渡,用于当属性发生变化时(例如让我们的动物跳跃)。

    .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});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 2010-10-03
      • 2014-02-16
      • 1970-01-01
      相关资源
      最近更新 更多