I am writing an application in Titanium for Android. I have a lot of code in a single JS file. I would like to know if there is any function like php's include to break the code into multiple files and then just include them.
Thanks
Use the CommonJS / RequireJS approach, specifically the require command. This is the (strongly) recommended way for dealing with large systems in Titanium, and is well documented on their website, along with many best practices for dealing with JavaScript modularization specific to Titanium. Here is the documentation from Titanium on this.
For example, to create a module that encapsulates a 'view' of some kind, put it in a file named MyCustomView.js with this content:
// MyCustomView.js
function MyCustomView(message) {
var self = Ti.UI.createView({
backgroundColor : 'red'
});
var label = Ti.UI.createLabel({
text : message,
top : 15,
.... // Other initialization
});
// ... Other initialization for your custom view, event listeners etc.
return self;
}
module.exports = MyCustomView;
Now you can easily use this module in another class, lets assume you put this in your /Resources folder, lets load the module inside app.js and add it to the main window.
// app.js
var MyCustomView = require('MyCustomView');
var myView = new MyCustomView('A message!');
Titanium.UI.currentWindow.add(myView);
You can use this approach to make custom views, libraries of reusable code, and anything else you would like. Another common thing would be to have a Utility class that has many different helper functions:
// Utility.js
exports.cleanString = function(string) {
// Replace evil characters
var ret = string.replace(/[|&;$%#"<>()+,]/g, "");
// replace double single quotes
return ret.replace(/"/g, "''");
}
This method can be easily used like this:
// app.js
var Utility = require('Utility.js');
Ti.API.info(Utility.cleanString('He##o W&orld$'));
Another common method I use it for is to implement the Singleton pattern as each module loaded is its own functional context, so if you like, you can have values that persist:
// ManagerSingleton.js
var SpriteManager = {
count : 0
};
exports.addSprite = function() {
SpriteManager.count++;
}
exports.removeSprite = function() {
SpriteManager.count--;
}
You would load and use this much the same way as Utility:
// app.js
var ManagerSingleton = require('ManagerSingleton');
ManagerSingleton.addSprite();
This is something of a more elegant solution instead of using global variables. These methods are by no means perfect, but they have saved me a lot of time and frustration, and added depth, elegance, and readability to my Titanium code for Apps of all sizes and types.
There are two dominant module systems in the Javascript world.
One is the CommonJS and the second is AMD. There is a lot of discussion about which one is best and for what purpose. CommonJS is more widely used for server side JS while AMD is used mostly for browser JS.
RequireJS (requirejs.org) seems to be the most popular AMD system.
For information on JS module systems please read here: http://addyosmani.com/writing-modular-js/
Related
I have a pretty big javascript legacy code base of a WebApplication, which includes the presentation/data model/controller/connectivity. I'm trying to replace the presentation layer technology with ReactNative, while keep the existing data model/controller/connectivity parts. So the first question is, after I built the ReactNativeComponent where we have the UI layout defined, binding established, styles created... but I need to call some js functions from the legacy code.
How can I require/import an existing js file (not a ReactNativeComponent) to one ReactNativeComponent and use it?
I've had this problem before too. Something I did, unable to find more elegant solutions, was to wrap my legacy code in a module.
Let's say this is foo.js
var Foo = (function() {
var mod = {
init: function() {
// legacy code here...
}
}
return mod;
})()
module.exports = Foo;
then in calling file:
import foo from './somewhere/foo';
foo.init();
I didn't love this approach, but it worked. Hopefully it can somewhat help.
If they're purely js then you can import them normally. If they have anything to do with html/css/dom it will throw an error.
Around one year ago we started a web system that over the time has grown quite a bit. From the beginning the goal was to build reusable code that would speed up the development of future projects, and it has. With every new project, the reusable code from the previous was taken and build upon it.
At the moment, the server side code is really clean, and there is a clear separation between the "framework" (generic functionality) and the project specific logic.
However, the javascript has grown out of control. For the page specific javascript (button events, ajax calls, etc.) we've been using closures and the module pattern. But the javascript common files (the ones we import in every page), are full of functions with no association between them beyond some similarities on the names.
Because of this I'm now trying to build a sort of framework (easily reusable and maintainable code) encapsulating the logic and functions we already have. It should be one "core" object and several optional "extensions". They would be in separate files to improve the order of the code. Specifically, I'm trying to achieve the following:
Encapsulation of the code to prevent name collisions. We are very comfortable with the private/public separation of the closures.
Extendable functionality, something like the open/close principle. The tricky part here is that an extension might want to access a private method of the core.
I've been reading a lot on OO in javascript, and I've even tried to understand how jQuery does it, but I'm still unable to get my head around it. For the architectural side, it seems that I should be building a module or service framework, but the ones I've found are much more complex than what I want to achieve.
If it weren't for the tricky part mentioned earlier, a simple $.extension() would do, but I'm stuck in the how to access a core private method from an extension part. In short, my question would be: Is there a recommended architecture in javascript to build something like the following example?
var framework = function () {
//Private variable
var internalState = 1;
//Private method
var validState = function () { ... }
//Public methods
return {
commonTask1: function () { ... },
commonTask2: function () { ... }
}
}();
framework.addMoreFunctionality(function () {
var specificData = '';
return {
extensionMethod: function () {
//TRICKY PART HERE
if (core.validState()) { ... }
}
}
}());
Just return a function from the framework module.
return {
isValidState: function() { ... }
commonTask1: function () { ... },
commonTask2: function () { ... }
}
The isValidState function could then check the internal state.
// isValidState
function() {
if (validState()) {
return true;
}
return false;
}
Check if the state is valid then by calling core.isValidState(); Like this you will not get any reference to any "private" variable inside the framework core because the functions returns a bool and not a direct reference to any objects.
Have you explored DOJO ? It has module system, a build system and very elaborate OO framework implemented.
You can have your own modules / "base Dijits" that will help you implement "generic modules/widgets" and then extend them per-project, by writing / adding specific capabilities the way you have described.
DOJO is not exactly in Vogue, but if your application deals with forms like interface, then it's definitely a candidate.
I'm working on a project written using Require.js. There are a number of reused functions that are currently being called from the global scope. These functions involve ui transitions, hide/show, and general on hover events. I want to organize these functions right into require, but not quite sure where/how to include them.
For example let's say in the app there are multiple spots that may call a common function of showDropdown(). And let's say it requires jQuery for the animation. Where or how would be the best place to store the showDropdown function?
Say a simple function like:
function showDropdown(id) {
var thisdropdown = $(id).find('.dropdown');
$(thisdropdown).slideDown();
}
I could create a UI folder, with the different js functions all being their own file. Then simply require them on any other files that are dependent on them. But regardless, those files will need to export their function to the global scope to be accessible correct?
I feel there is an obvious answer/setup as this must be fairly common item.
In addition, I am writing this in a backbone app, but I don't believe that has any direct impact, more of a require.js question.
Create a util library or something like that:
// util.js
define({
showDropdown: function(id) {
var thisdropdown = $(id).find('.dropdown');
thisdropdown.slideDown();
}
});
Then use it elsewhere:
require(['util'], function(util) {
util.showDropdown('my-id');
});
I'm interested in using more fine-grained Javascript include files to enhance maintainability. However, I'm missing something. Can I still "overwrite" or include sections from my Razor view context? Let's say my Javascript include is as follows:
function CategoriesViewModel() {
var self = this;
self.searchMode = ko.observable("SEARCH"); // Wire up with Knockout.js
}
But, if this script were inline as part of my .cshtml Razor view, I'd be able to do something like this:
function CategoriesViewModel() {
var self = this;
self.searchMode = ko.observable("SEARCH"); // Wire up with Knockout.js
self.categories = #Html.JSONFor(Model.LookupForCategories.Select(c => c.Text ));
}
(Without the syntax highlighting, I'll point out that I've included a server tag that places some Javascript code/data straight from my server-side ASP.MVC ViewModel.)
If I pull Javascript into separate files and include them, I lose this ability. Is there a feature or technique that I'm missing?
I haven't used it yet myself but you may be interested in the RazorJs nuget package: http://nuget.org/packages/RazorJS
More on the subject from the author here:
http://djsolid.net/blog/razorjs---write-razor-inside-your-javascript-files
Sadly no. This is a common problem when dealing with serverside frameworks and js. You are pretty much stuck with parameterizing, or declaring variables either as globals, or as properties on some shared object.
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" ?
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.
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
I defer to Douglass Crockford on all matters pertaining to JavaScript best practices.
Here is his homepage: http://javascript.crockford.com/.
Here is a great book on what to do and what not to do in JavaScript. http://www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwideweb
Here is his amazing tool which can automatically tell you if you are employing any worst practices. http://www.jslint.com/
As to the prototype question, you use prototype when you want to employ prototypal inheritance, or create a "static" class function which will be present for all instances of that class without consuming memory for each instance.
Require.js is great tool, you can use it also on the client side. But be careful when you use it on mobile. In such case you should either use the editor to navigate better in one file or use thing like sprocket. It is a "precompiler", does not put any additional library to your code.
I passed through your sliced up code. Probably you should define the different parts as modules, read the requirejs documentation for defining modules, it gives good assistance.
But think twice whether you really need for organizing your code an extra library.
In case you are building something more complex, for example with multiple product modules and sub modules, I recommend creating a context hierachy for your modules. Also make the UI components to be self-contained so that you have templates, css, logic, assets, localization etc for a particular UI component in a single place.
If you need to refer a reference architecture for large scale js development see http://boilerplatejs.org. I'm the main author of it and it demonstrates a lot of patterns that are useful in complex product development.