So Im building an app and I'm trying to implement the structure of the app so that its robust and scalable in future.
My app is mostly divided into JavaScript Modules (revealing pattern):
// filter.js file //My javascript module structure var filter = (function(){ var _privateMethod = function(){ } var publicMethod = function(){ _privateMethod(); } return{ publicMethod: publicMethod } });
Now the main issue is that I want to use AngularJS within my app too and AngularJs has its own angular modules like so:
// app.js file var myApp = angular.module('myApp',[]); myApp.controller('myController', function($scope){ });
The way I have planned my app developed is:
- All HTTP calls to the server will be done within my JavaScript module or to be more clear within my "filter.js" file (see above)
- Returned data from the HTTP calls to server will then be sent back to angularjs controller or in my case the "app.js" file (see above) and that controller/app.js file will be responsible for updating my view/html file.
The reason for doing this is so that all my functions that connect with server and handle data are within a private scope (the filter.js module) and no one should have access to those functions as they are being kept out of the global scope.
But to pass data from my filter.js file to my Angular app.js controller I had to use callbacks.
Below is the complete code of my above described scenario:
filter.js
var filter = (function(){ // public method var testMethod = function(callback){ loadDoc(function(dta){ alert(dta); callback(dta); }) }; // private Method function loadDoc(callback) { // Create the XHR object to do GET to /data resource var xhr = new XMLHttpRequest(); var dta; xhr.open("GET","url",true); // register the event handler xhr.addEventListener('load',function(){ if(xhr.status === 200){ //alert("We got data: " + xhr.response); dta = xhr.response; callback(dta); } },false) // perform the work xhr.send(); } return { testMethod: testMethod }; })();
app.js:
var myApp = angular.module('myApp',[]); myApp.controller('myController', function($scope){ $scope.myFunc = function(){ filter.testMethod(function(dta){ alert(dta); $scope.test = dta; console.log($scope.test); }); }; });
You can see from my above code structure that I am using callbacks to send data back to my controllers.
My Question:
My question is that the above descried scenario of how I see my code implementation and structure, is that right approach?
Does the implementation adhere to good, clean and correct javascript code?
Is there something else I can do to improve my app's code structure?