Home › Forums › JavaScript › Structure of js code
- This topic is empty.
-
AuthorPosts
-
September 29, 2013 at 11:39 am #151631KuzyoParticipant
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.
September 29, 2013 at 1:30 pm #151636__ParticipantBrendan’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 thenewsWidget
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.September 30, 2013 at 8:53 am #151697KuzyoParticipantThanks @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 } }; })();
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.