1

In the following code, I want to be able to call bindClickEvents() like so:

App.Utils.Modal.bindClickEvents();

However, I don't understand the syntax necessary to do this.

Current code:

var App = new Object;

App.Modal = {
  bindClickEvents: function() {
    return $('a.alert-modal').click(function(e) {
      return console.log('Alert Callback');
    });
  }
};

$(document).ready(function() {
  return App.Modal.bindClickEvents();
});
Domenic
  • 105,522
  • 40
  • 210
  • 262
keruilin
  • 15,808
  • 32
  • 106
  • 174

3 Answers3

3

You can do it in one go:

var App = {
  Modal : {
    bindClickEvents : function () {/* ... */}
  }
}

or if you want to break that up to separate steps:

var App = {};
App.Modal = {};
Modal.bindClickEvents = function () {/* ... */};

BTW, in reference to your original question title, this is not object chaining. This is object composition. Object chaining is being able to call methods in an object multiple times in a single statement.

Domenic
  • 105,522
  • 40
  • 210
  • 262
slebetman
  • 101,977
  • 18
  • 125
  • 159
2

Is this what you're trying to do?

var App = {};

App.Utils = {};

App.Utils.Modal = {
  bindClickEvents: function() {
    return $('a.alert-modal').click(function(e) {
      return console.log('Alert Callback');
    });
  }
};

$(document).ready(function() {
  return App.Utils.Modal.bindClickEvents();
});
Dagg Nabbit
  • 72,560
  • 18
  • 107
  • 141
0

Prefer the object literal syntax to the Object constructor; some authors go so far as to call the latter an anti-pattern

Here's the simplest way to set up App.Utils.Modal.bindClickEvents();

var App = {
      Utils: {
           Modal: {
               bindClickEvents: function() {
                    return $('a.alert-modal').click(function(e) {
                        return console.log('Alert Callback');
                    });
               }
           }
      }
 };

Or you can piece it together one step at a time:

var App = {};
App.Utils = {};
App.Utils.Modal = {};
App.Utils.Modal.bindClickEvents = function() {
    return $('a.alert-modal').click(function(e) {
      return console.log('Alert Callback');
    });
};
Adam Rackis
  • 81,646
  • 52
  • 262
  • 388