简体   繁体   English

JavaScript对象文字:来自多个方法的相同事件绑定

[英]JavaScript object literal : same event binding from multiple methods

I'm trying to figure out what's the best way to bind event handlers from within object literal. 我正在尝试找出在对象常量内绑定事件处理程序的最佳方法是什么。

Imagine the following object: 想象以下对象:

MySystem.ValidationTop = {

    topClose : function() {

        "use strict";

        $(document).on('click', '#topCloseTrigger', function(event) {

            // some action goes here

        });

    },

    topExecute : function() {

        "use strict";

        $(document).on('click', '#topExecuteTrigger', function(event) {

            // some action goes here

        });

    },

    topWarningTemplate : function(thisWarning) {

        "use strict";

        // warning is wrapped and styled here

    },

    addTopWarning : function(thisWarning) {

        "use strict";

        if (typeof thisWarning !== 'undefined') {

            this.addTop($(this.topWarningTemplate(thisWarning)));
            this.topClose();

        }

    },

    topConfirmationTemplate : function(thisConfirmation) {

        "use strict";

        // confirmation is wrapped and styled here

    },

    addTopConfirmation : function(thisConfirmation) {

        "use strict";

        if (typeof thisConfirmation !== 'undefined') {

            this.addTop($(this.topConfirmationTemplate(thisConfirmation)));
            this.topClose();

        }

    }

};

The problem here is that the method addTopWarning and addTopConfirmation can be called multiple times from other objects and this will effectively also call the topClose and topExecute multiple times and create duplicate bindings to the same objects. 这里的问题是,方法addTopWarningaddTopConfirmation可以从其他对象多次调用,这也将有效地多次调用topClosetopExecute并创建到相同对象的重复绑定。 I know I could convert it to the instance object, which initialises all of the bindings when the instance of the object is created, but again - with multiple instances of the same object the bindings will occur several times as well. 我知道我可以将其转换为实例对象,该实例对象在创建该对象的实例时会初始化所有绑定,但是同样,对于同一对象的多个实例,绑定也会发生多次。

I'd prefer to keep it as object literal as this specific object serves more as a helper than object that needs to be instantiated. 我宁愿将其保留为对象字面量,因为此特定对象比需要实例化的对象更多地充当了助手。

I can't figure out how to approach it so if someone could advice please - it would be very much appreciated. 我不知道该如何处理,因此如果有人可以提出建议,我将不胜感激。

With jQuery's event namespaces you can do this: 使用jQuery的事件名称空间,您可以执行以下操作:

$(document)
      .off('click.myValidation')
      .on('click.myValidation', '#topCloseTrigger', function(event) {
        // some action goes here
      });

the .off() above will ensure that only one handler is set for that event. 上面的.off()将确保仅为该事件设置一个处理程序。

Use something to check if the function has already been run. 用一些东西检查功能是否已经运行。

Here is an example with a closure 这是一个带有闭包的例子

function  validationTop(/* some args */){
    var trigger = {'conf':true, 'warn':true};

    return {
        topConfirmation: function(){
            if(trigger['conf']){
                //do some stuff
                trigger['conf'] = false;
            }
        }

        //rest of your object
    }   
}

To stop it from binding agian 阻止它绑定agian

MySystem.ValidationTop = {
  topClosed : 0,
  topExecuted : 0,
  topClose: function(){
    "use strict";
    if(!this.topClosed){
      this.topClosed = 1;
      $(document).on('click', '#topCloseTrigger', function(event) {
        // some action goes here
      });
    }
  }
}

repeat 重复

Across multiple instaces: 跨多个实例:

var topClosed = 0, topExecuted = 0;
MySystem.ValidationTop = {
  topClose: function(){
    "use strict";
    if(topClosed){
      topClosed = 1;
      $(document).on('click', '#topCloseTrigger', function(event) {
        // some action goes here
      });
    }
  }
}

If you need multiple instances of an Object: 如果需要一个对象的多个实例:

if(!Object.create){
  Object.create = function(o){
    function F(){}
    F.prototype = o;
    return new F;
  }
}

Now just use var whatever = Object.create(MySystem.ValidationTop); 现在只需使用var whatever = Object.create(MySystem.ValidationTop);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM