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();
});
3
  • Always use {} instead of new Object Commented Jan 6, 2012 at 5:20
  • why is that if u don't mind me asking? Commented Jan 6, 2012 at 6:05
  • See this question: stackoverflow.com/questions/251402/… Commented Jan 6, 2012 at 6:51

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I guess OP didn't actually want a Utils object in there :-)
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');
    });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.