keruilin
keruilin

Reputation: 17512

javascript object composition syntax

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

Upvotes: 1

Views: 607

Answers (3)

Adam Rackis
Adam Rackis

Reputation: 83356

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');
    });
};

Upvotes: 0

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

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

Upvotes: 2

slebetman
slebetman

Reputation: 113896

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.

Upvotes: 3

Related Questions