在javascript对象文字中声明事件

时间:2018-11-01 11:45:10

标签: javascript jquery event-handling

通常,当我使用对象文字样式的javascript时,我会通过以下方式为页面加载事件:

var myObject = {
    button: $('button'),
    init: function() {
        button.on('click', $.proxy(this.myMethod, this));
    },
    myMethod: function(event) {
        alert('Hello');
    }
};
myObject.init();

现在我想在我的config属性中拥有一系列事件

var myObject = {
    bindActions: [
        $('#employee_data').on('click', $.proxy(this.myMethod, this))
    ],
    init: function() {
        // here I assume I need to do something like this 
        // to load all events from this.bindActions
        // this.bindActions.forEach(function(action) {

        //     ?????? 

        // });

    },
    myMethod: function(event) {
        alert('Hello');
    };
};
myObject.init();

请帮助我弄清楚如何在循环中附加此事件,并提供一些解释? 提前非常感谢

1 个答案:

答案 0 :(得分:0)

除非有特定原因要循环访问数组(也许可以更好地控制绑定的事件以及何时进行?),否则最好将bindActions转换为在以下情况下执行的函数本身您这样运行myObject.init()

var myObject = {
    bindActions: function(){
        $('#employee_data').on('click', $.proxy(this.myMethod, this));

        // bind as many as you want here
        //$('#employee_data').on('..', ...)
    },
    init: function() {
        // bind all events in bindActions when init() is executed
        this.bindActions(); 
    },
    myMethod: function(event) {
        alert('Hello');
    };
};

myObject.init();