Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript structure, right way?

Iam trying to get better in javascript coding. Away from 1000 lines of code in one file. But iam not sure if this is the "right" way:

RequireJS to load files when needed inside "boot.js":

require([
    "library/jquery.form/jquery.form",
    "app/eventManager",
    "app/myapp"
], function() {
    $(function() {
        MyApp.init();
    });
});

MyApp.js

var MyApp = {
init: function() {
    MyApp.mainController();
},

// this is our controller, only load stuff needed..
mainController: function() {

    //controller = set from php/zendframework
    switch (controller) {
        case 'admin':
            MyApp.initAdmin();
            break;
        default:
            break;
    }
},

// action for admin controller
initAdmin: function() {
    //lazy load
    require(["app/admin/admin"], function(){
        MyApp.admin.init();
    });
}};

MyApp.admin.js

MyApp.admin = {
init : function() {
    if (permisson != 'admin') {
        console.log('Permission denied.');
        return false;
    }
    MyApp.admin.dashboard.init();
}

};

MyApp.admin.dashboard = {

init: function() {
    MyApp.admin.dashboard.connectEventHandlers();
    MyApp.admin.dashboard.connectEvents();
    MyApp.admin.dashboard.getUserList('#admin-user-list');
},

connectEvents: function () {
    EventManager.subscribe("doClearCache", function() {
        MyApp.admin.dashboard.doClearCache(url);
    });

    EventManager.subscribe("doDeleteUser", function() {
        MyApp.admin.dashboard.doDeleteUser(url);
    });

},

What other "styles" are common? or this a goodway to structure code? THere a lot of examples in the net, but i was not able to find "real life" code..

And one of biggest "problems" when does i need ".prototype" ?

like image 928
opHASnoNAME Avatar asked Jan 20 '23 22:01

opHASnoNAME


2 Answers

JavaScript Patterns is a good reference for various ways of structuring code.

It would also be a good idea to study the source code of libraries such as jQuery.

like image 139
Kristopher Johnson Avatar answered Jan 30 '23 11:01

Kristopher Johnson


One change I would make to your code is to avoid repeating 'event' strings everywhere. You could reduce this by doing something like:

var app = {

      events : {

         someEvent : "someEvent"

      }

}

EventManager.subscribe(app.events.someEvent, someFn);

EventManager.publish(app.events.someEvent);

I would also avoid calling console.log directly and use a wrapper such as this which provides a fallback if not console is available

N.B Angus Croll has a decent blog where he mentions js structure/namespacing etc

and there is some really good knowledge being shared over at JsMentors from well versed js ninjas

like image 31
redsquare Avatar answered Jan 30 '23 11:01

redsquare