0

我试图弄清楚从对象文字中绑定事件处理程序的最佳方法是什么。

想象以下对象:

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

        }

    }

};

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

我更愿意将它保留为对象文字,因为这个特定对象比需要实例化的对象更像是一个帮助器。

我不知道如何处理它,所以如果有人可以提供建议 - 将不胜感激。

4

3 回答 3

2

使用 jQuery 的事件命名空间,您可以这样做:

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

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

于 2014-07-22T22:45:13.897 回答
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
    }   
}
于 2014-07-22T22:37:21.813 回答
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
      });
    }
  }
}

如果您需要一个对象的多个实例:

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

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

于 2014-07-22T22:38:22.757 回答