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
  • 110,262
  • 41
  • 219
  • 271
keruilin
  • 16,782
  • 34
  • 108
  • 175

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
  • 110,262
  • 41
  • 219
  • 271
slebetman
  • 109,858
  • 19
  • 140
  • 171
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
  • 75,346
  • 19
  • 113
  • 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
  • 82,527
  • 56
  • 270
  • 393