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

时间:2014-07-22 22:19:36

标签: javascript javascript-objects event-binding

我试图找出从对象文字中绑定事件处理程序的最佳方法。

想象一下以下对象:

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();

        }

    }

};

这里的问题是方法addTopWarningaddTopConfirmation可以从其他对象多次调用,这有效地也可以多次调用topClosetopExecute创建重复绑定到相同的对象。我知道我可以将它转换为实例对象,它在创建对象实例时初始化所有绑定,但是再次 - 对于同一对象的多个实例,绑定也会多次出现。

我更喜欢将其保留为对象文字,因为这个特定对象更像是一个帮助器而不是需要实例化的对象。

我无法弄清楚如何处理它,如果有人可以提出建议 - 非常感谢。

3 个答案:

答案 0 :(得分:2)

使用jQuery的事件命名空间,您可以执行以下操作:

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

上面的.off()将确保只为该事件设置一个处理程序。

答案 1 :(得分:0)

使用某些东西检查该功能是否已经运行。

这是一个带闭包的例子

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
    }   
}

答案 2 :(得分:0)

阻止它绑定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
      });
    }
  }
}

重复

跨多个实例:

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

如果您需要Object的多个实例:

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

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