Exposing application scripts to certain scripts only - javascript

uhh it's hard to come with a right title for this problem excuse me.
In a backbone.js application i am building. Models, Views, Templates are all in separate javascript, html files. I want to export the Models, Views and Templates to the application bootstapper file (app.js) without polluting the global variable i.e doing window.App.Model = myModel; that. By export i mean make the code inside the files available to app.js for initialization and running
How do i go about doing this?
Are there any patterns that will solve the problem? Could you provide me a example
Description
In cases where models,views and templates are split to many disparate files the application bootstrapper file app.js should have some means to access these M,V,C components. Hence common approach is to do below inside the model.js file
window.App.Model.PersonModel = Backbone.Model.extend({});
App.js
var instance = new window.App.Model.PersonModel();
var personView = new window.App.Views.PersonView({model:instance});
Finally you see that everything derives from the Global object App which i think is not safe, improper and weak way to build application dependencies
Suggestions
Just to the above question, could someone suggest a template loading library(javascript templates regardless of engine used) that can be used to load the templates

Take a look on RequireJS, which support asynchronous module definitions/loading. You would have to rewrite your modules to and app.js to satisfy AMD api, but it would take only few strings of code.

Related

How do you split up large controllers into multiple files in Express?

I'm building an express application which up until now has used a singular controller file named users. This contains various user related functions such as signUp/signIn/getPersonalInfo, which are exported using module.exports, and required in the router.
The problem is this file is now getting rather large and I would ideally like a folder structure such as the following:
controllers/users/registration.js
controllers/users/personalInfo.js
How can I do this such that I can still just require a single file in my router:
var users = require('../controllers/users/?');
and still have access to all the functions within each controller.
Also if there is a more efficient way of doing so please let me know.
Not sure if this is what you are looking for but in my project make use of multiple functions with only one reference to my 'bootcamps' controller.
const {
getBootcamps,
getBootcamp,
createBootcamp,
updateBootcamp,
deleteBootcamp,
getBootcampsInRadius,
bootcampPhotoUpload
} = require('../controllers/bootcamps');
Feel free to take a look at my project for inspiration:
https://github.com/KristoferMar/NodeJs-Guide/blob/master/routes/bootcamps.js

Using stickit with Backbone in Webpack

I'm migrating my code from 'vanilla' to WebPack. Previously the backbone.js and backbone.stickit.js were loaded in index.html so that the code that was running later has seen stickit() function under Backbone.View.prototype (which is what my views extend from.
However, after migrating to WebPack I've started getting errors, that this.stickit() is not defined, which I've get rid of via adding the require to every JS file defining views extending from Backbone.View:
import Backbone from 'backbone';
require('backbone.stickit/backbone.stickit');
I don't feel good about that solution. In that specific case it is not so bad becasue my views explicitely use stickit. However, there are modules and extensions that alter the default behaviour, and I'd like to define them in one place.
How should I go about handling it? I've got a concept of importing Backbone, applying all plugins, and re-exporting it:
import Backbone from 'backbone';
require('backbone.stickit/backbone.stickit');
....
const Backbone2 = Backbone;
export {Backbone2};
which looks a bit too tricky...
How should I go about it? Shouldn't the webpack layer contain only one copy of Backbone after build, no matter in how many places it was imported, and which plugins were required?

Dynamic loading of modules and components at runtime in Angular 4

I've been looking to develop a method for loading modules and/or components into an AOT-compiled Angular 4 application and been stymied by a variety of solutions that never quite seem to get me where I want to be.
My requirements are as such:
My main application is AOT compiled, and has no knowledge of what it is loading until runtime, so I cannot specifically identify my dynamic module as an entry component at compile time (which is explicitly necessary for the 'dynamic' component loading example presented on Angular.io)
I'd ideally love to be able to pull the code from a back end database via a GET request, but I can survive it simply living in a folder alongside the compiled site.
I'm using Webpack to compile my main application, breaking it into chunks - and so a lot of the SystemJS based solutions seem like dead ends - based on my current research, I could be wrong about this.
I don't need to know or have access to any components of my main application directly - in essence, I'd be loading one angular app into another, with the dynamically loaded module only perhaps having a few tightly controlled explicit interface points with the parent application.
I've explored using tools like SystemJsNgModuleLoader - which seems to require that I have the Angular compiler present, which I'm happy to do if AOT somehow allowed me to include it even if I'm not using it elsewhere. I've also looked into directly compiling my dynamic module using ngc and loading the resulting ngfactory and compiled component/module, but I'm not clear if this is at all possible or if so - what tools Angular makes available to do so. I have also seen references to ANALYZE_FOR_ENTRY_COMPONENTS - but can't clearly dig up what the limitations of this are, as first analysis indicates its not quite what I'm looking for either.
I had assumed I might be able to define a common interface and then simply make a get request to bring my dynamic component into my application - but Angular seems painfully allergic to anything I try to do short of stepping outside of it alltogether and trying to attach non-angular code to the DOM directly.
Is what I'm trying to do even possible? Does Angular 2+ simply despise this kind of on the fly modification of its internal application architecture?
I think I found an article that describes exactly what you are trying to do. In short you need to take over the bootstrap lifecycle.
The magic is in this snippet here.
import {AComponentNgFactory, BComponentNgFactory} from './components.ngfactory.ts';
#NgModule({
imports: [BrowserModule],
declarations: [AComponent, BComponent]
})
export class AppModule {
ngDoBootstrap(app) {
fetch('url/to/fetch/component/name')
.then((name)=>{ this.bootstrapRootComponent(app, name)});
}
bootstrapRootComponent(app, name) {
const options = {
'a-comp': AComponentNgFactory,
'b-comp': BComponentNgFactory
};
https://blog.angularindepth.com/how-to-manually-bootstrap-an-angular-application-9a36ccf86429

Using require.js for client side dependancies in Adobe CQ5

I was wondering if anyone had experience using require.js with the Adobe CQ5 platform. I'm writing a Chaplin.js(backbone-based) single page app that will be integrated into the rest of CQ5-based site we're working on. Chaplin requires the use of a module system like AMD/Common.js and I want to make sure my compiled javascript file will usable within CQ5's clientlibs. Is it as simple as adding require.js as a dependency in clientlibs prior to loading in my javascript modules? Someone's insight who has experience in doing this would be greatly appreciated.
I've implemented this as a solution of organize in a better way all the modules such as:
//public/js/modules/myModule.js
define('myModule',[ /* dependencies */] ,function( /* stuff here */ ))
and in the components such:
<% //components/component.jsp %>
<div>
<!-- stuff here -->
</div>
componentJS:
//components/component/clientlibs/js/component.js
require(['modules/myModule']);
and finally I've configured require (config.js) and I've stored the JSs modules in a new different design folder. Located the compiled JS after close </body> to guarantee the JS is always located at the bottom after the HTML.
<!-- page/body.jsp -->
...
<cq:includeClientLib js="specialclientlibs.footer"/>
</body>
solving with this the issue of have "ready" all the content before the JS is executed. I've had some problems to resolve with this async stuff managed for the clienlibs compilation tool, in production the problem was different, however, in development, the order in what CQ compiles the JS has produced me some lacks in terms of order of the JS. The problem really was a little bit more complex than the explanation because the number of JS was really big and the team too, but in simple terms it was the best way I've discovered so far..
The Idea
I think you can compile your Chaplin.js with one of the AMDShims to make it self contained, wraps every dependencies it needs inside a function scope, expose an entry point as global variable (which is a bad practise, but CQ do it all the time...) and then use the compiled.js inside a normal clientlib:
AMD Shims
https://github.com/jrburke/requirejs/wiki/AMD-API-Shims
Example
Here is an example of how we make the one of our libs self-contained:
https://github.com/normanzb/chuanr/blob/master/gruntfile.js
Basically, in source code level the lib "require"s the other modules just as usual. However after compiled, the generated chuanr.js file contains everything its needs, even wrapped a piece of lightweight AMD compatible implementation.
check out compiled file here: https://github.com/normanzb/chuanr/blob/master/Chuanr.js
and the source code: https://github.com/normanzb/chuanr/tree/master/src
Alternative
Alternatively rather than compile every lib you are using to be independent/self-contained, what we do in our project is simply use below amdshim instead of the real require.js. so on cq component level you can call into require() function as usual:
require(['foo/bar'], function(){});
The amd shim will not send the http request to the module immediately, instead it will wait until someone else loads the module.
and then at the bottom of the page, we collect all the dependencies, send the requirements to server side handler (scriptmananger) for dynamic merging (by internally calling into r.js):
var paths = [];
for (var path in amdShim.waiting){
paths.push(path);
}
document.write('/scriptmananger?' + paths.join(','));
The amdShim we are using: https://github.com/normanzb/amdshim/tree/exp/defer

emberjs - best practice to built an app?

I'm here cause I ask me some questions about emberjs framework and the best way to built an app with it... There are some questions that I hope someone can answer to me :
Is there any built-in system to manage memory efficiently ?
How to manage the controllers/views/models to be instanciated and destroyed during the app lifecycle ?
Have we to declare all our controllers and views at the starting of the app ?
Is there a way to auto-instantiate an view's controller when a the view is added to the DOM by the main controller (or the stateManager) ?
To resume my situation, I've testing ember's features and understanding all of that pretty well. But now, I'm a little bit confusing and don't know how to structure my app. When to instanciate views and its controllers, where and when to destroy view's controller for memory performance, etc...
Is there some of you that have been like me at this time and have some answers for me ?
All answers and help is really appreciated and I thank you already now for your feedback(s)
See you guys !
Edit : I'm using emberjs with requireJs to be able to separate my javascript files. Is there any best solution or built-on one to do that ?
(sorry for my english)
These links should help.
https://stackoverflow.com/questions/9241735/tutorial-or-pdf-for-ember-js
http://ngauthier.com/2012/02/playing-with-ember.html
http://www.infoq.com/articles/emberjs
requirejs isnt suitable for emberjs, Ember is build on top of a simpler require() from minispade.js, which isnt AMD.
Someone suggested me 2 cool grunt tasks to work with ember.js
grunt-neuter : just use require('module'), so neuter can concat your app in the right order
grunt-ember-template : compiles your template file into one global template.js, easy to work with.
i personally manages my app like HMVC, and i require each module files into its own moduleController, my app.js only inits each modules index controller, so i know what module is loaded when i look at my app.js
- app.js
- modules/
-- module1
- module1Controller.js // initiate this in the app.js, which ain't required for ember
- module1Model.js // (if non ember) returns static methods that can be used by other modules
- module1View.whatever // this should be compiled into the template.js, just easier to manage in the same folder
-- module2
-- module3 ...

Categories

Resources