1

I'm trying to emulate the module pattern found here: https://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/

Here is my code:

var RPSLS_UI = {
settings: {
    playerSelections: $(".card")
},

init: function() {
    this.bindUIActions();
},

bindUIActions: function() {
    this.settings.playerSelections.on("click", function() {
        console.log($(this));
    });
}
};

I have included the dependencies in my HTML in this order:

<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script type="text/javascript" src="assets/js/rpsls-ui-1.0.js"></script> <script type="text/javascript" src="assets/js/index.js"></script>

When I load my HTML, I type in console:

RPSLS_UI.init();

Results in:

undefined

Then I type in:

RPSLS_UI.init;

Results in:

function () { this.bindUIActions(); }

What is happening here? Why is the init() function undefined?

1 Answer 1

1

The function isn't undefined. It returns undefined because there is no return statement. If you want it to return something you could add a return statement to it:

init: function() {
    this.bindUIActions();
    return 'Hi!';
}

It doesn't seem like it is necessary for it to return anything, as it calls another function that binds a click handler to your DOM. The function has side effects, but doesn't return anything.

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

3 Comments

Thanks! That makes sense! I was really confused because my click event never fires off. I guess that's a separate question now.
@iparke Are there any errors in your console? My first guess is that you are including that script in the DOM before any elements with the class card exist. The expression $(".card") needs to run after the elements exist (IE. put the script right before your closing </body> tag, or anywhere else as long as it's after all the cards in your DOM). You could always check RPSLS_UI.settings.playerSelections.length to see how many elements matched the selector
2 for 2. Thank you so much.

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.