Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Structure of js code

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #151631
    Kuzyo
    Participant

    Hi, everyone.

    I have read this interesting article https://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/ and wrote simple application using this technic, but in comments everyone wrote about problem with global “s”, and as for me no one write understandable solution. Can somebody help me to find one. Appreciate your help. Thanks.

    #151636
    __
    Participant

    Brendan’s comment sums up a very good solution.

    The problem they’re talking about is global scope: basically, naming conflicts. If you define someVar here, then you have to remember that you can’t use that variable name anywhere else, or you’d have a collision, and the first value would be lost – probably breaking things.

    In a more academic perspective, s is logically part of the newsWidget object, and so should be inside that object (rather than outside, in the global scope, where it might get smashed).

    By wrapping the whole thing in a self-executing function, you create a closure around s: it’s still available to the newswidget (me in Brendan’s example), but it can’t be reached from the global scope, or anywhere else.

    #151697
    Kuzyo
    Participant

    Thanks @traq, I uderstood. I found similar solution, but without ** me**:

    var NewsWidget = (function () {
        var s; // private alias to settings
    
        return {
            settings: {
                numArticles: 5,
                articleList: $("#article-list"),
                moreButton: $("#more-button")
            },
    
            init: function() {
                s = this.settings;
                this.bindUIActions();
            },
    
            bindUIActions: function() {
                s.moreButton.on("click", function() {
                    NewsWidget.getMoreArticles(s.numArticles);
                });
            },
    
            getMoreArticles: function(numToGet) {
                // $.ajax or something
                // using numToGet as param
            }
    
        };
    })();
    
Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.