Skip to content
Advertisement

Bind a method of an object to an event of an element

I want to bind a method of an object to an event of an element. For example:

function ABC()
{
   this.events_list = function() {
   }

   this.events_list.clickElement = function() {
      alert("hello world");
   }

   this.bindEvents() = function() {
       $("#element").click(this.events_list.clickElement);
   }
}

var _abc = ABC();
_abc.bindEvents();

The above code is not binding the click event to clickElement method.

Advertisement

Answer

Does #element exist before you call _abc.bindEvents(). You can wrap it all in

$(document).ready(function() {
    var _abc = ABC();
    _abc.bindEvents();
});

function ABC()
{
   this.events_list = function() {
   }

   this.events_list.clickElement = function() {
      alert("hello world");
   }

   this.bindEvents() = function() {
       $("#element").click(this.events_list.clickElement);
   }
}

Will need to see more of your use case to do more.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement