variables with requieJS - javascript

My call to requireJS in on my index page, what I want to know is it possible for me to get a variable out of a function that is on my index page and use it as a condition in my main.js file? I am trying to have a script be used based on a variable on my index page.

If you want your wariable to be accesible on both index and main pages, then create separate requireJS module, put yuor variable in there and reference this module wherever you need it.
So, assuming that you already have two modules: index.js and main.js, you can create third module, let's call it "myVariables.js". Create that file and inside put something like this:
define(function() {
var vm = {
myGlobalVariable = "Hello"
};
return vm;
});
Then in your other modules you can reference to this module, for example like this:
var myVariabledModule = require('myVariables');
alert(myVariablesModule.myGlobalVariable);
This should give you and allert with the "Hello" string and this code should work in any module of your application.

Related

Requiring In Classes in Node

I am trying to require in some classes in Node, but I require them in through a single file which holds an object of all the individual requires. Like so -
File: /classes/controller.js
module.exports = class Controller {}
File: /classes/model.js
module.exports = class Model {}
File: /classes/classes.js
module.exports = {
Controller: require('./controller.js'),
Model: require('./model.js')
}
Then in app.js
const classes = require('./classes/classes.js');
....code.....
....more code.....
const someController = new classes['Controller'];
The thing is, this works just fine - but only for the first file that requires in the 'classes' variable. Any subsequent files that need to also require 'classes' in, ends up holding only an empty object inside of the 'classes' variable (and no, the actual variable name does not matter, as I tried using a different variable name in the second file but it still wound up storing an empty object). For instance, I often need my Controller to implement a Model class.
So once app.js calls controller.js, inside of that -
File: /classes/controller.js
const classes = require('./classes.js');
module.exports = class Controller {
constructor(var) {}
someMethod() {
....code....
const someModel = classes['Model'];
}
}
I can call a 'console.log(classes)', and it will print out '{}', but again this is only if it is done inside of 'controller.js' and only after being called from inside of 'app.js'. It will print out all of the classes as expected if the 'console.log()' is done either inside of 'app.js', or if 'controller.js' is called directly instead of through 'app.js'. Which is how I know where/how the error is occurring. The specific error being thrown is -
classes.Model is not a constructor
So that is where my question/problem comes in, because as I said I have called other objects in multiple files without ever running into this problem. So it must have something to do with how classes are implemented, correct? And although I do not understand the specifics of how it works, I roughly know that when a file is required in, in Node, after that it uses that same reference for any subsequent files - correct? So I was thinking it must somehow be the interplay of those two things, but I have no idea after that fact nor if I am even correct in assuming that is the problem.
You have a circular dependency of require() statements. This causes one of the require() to just return an empty object. You can't do that.
Inside of controller.js, you have require('./classes.js');.
Inside of classes.js, you have require('./controller.js').
So, each refers to the other which is what causes the circular dependency.
You will need to restructure the way code is laid out into files so you don't have this. Sometimes, the simplest fix is to just combine a couple functions into one file rather than having them all in separate files that are vulnerable to this issue. I don't quite understand your overall design to know what best to suggest in this case.
If nobody else besides controller.js is really going to use classes.js, then you can just move that code into controller.js (where you don't need to require in controller.js any more).

Access javascript variable in component in Angular 5

I have a js file in my Angular application, data.js . This js file has some variables declared in it, something like below.
var data = 'test'
Now I have to access these variables and their values in my component (app.component.ts).
I read some where that declaring them as exports make them into modules and those can be accessed anywhere, But I'm not sure how this can be done.
This is the structure of my application. I have data.js in assets->js folder.I need to modify the variable value in app.component.ts.
I'm very new to Angular. Is this even possible?
With the file in your assets, I am guessing you are declaring it on the window. You will need the include the script in your index.html, and then access it on the window within your component via window.data. This is not really the recommended way of doing this unless your use case dictates it. The module approach you mentioned is preferred.
Next to your app.component.ts, create a file called data.ts, with:
export let data: string = 'data';
In your app.component.ts, import it using:
import { data } from './data.ts';
If you plan to not mutate that data, consider using the const keyword instead (in data.ts).
Directory structure
/app.component.ts
/data.ts
/...
Edit: Show Global Approach
You will need to include your script outside of the context of the Angular application. If you bootstrapped your application using the Angular CLI, you can add a reference to it in the cli configuration file. See this documentation on the topic.
That file will be included and will be available for access within your component on the window. The tricky part comes with typing and the Window. And example may look like this.
class AppComponent extends Component {
private data: string;
constructor() {
// Explicitly cast window as an any type. Would be better to type this, but this should work for you.
this.data = (<any>window).data;
}
}
(referrring to https://stackoverflow.com/a/42682160)
first you have to include the script into your src/index.html like
< script src="/assets/js/data.js">< /script>
important is that the above statement is placed before your angular root component tags
(< root-component>< /root-component> or < ion-app>< /ion-app> or something like that)
then you can simply write (for example inside app.component.ts ngOnInit function)
let varFromJsFile = window["data"] // varFromJsFile = 'test'
You want the variable to be a member of a Component class, not just a variable declared anywhere within a module.
If this doesn't make sense right away, you need to look more carefully at some basic Angular code samples.
Also, as long as you're using Angular and therefore TypeScript, it's better the declare variables using let or const.

Using yeoman-generator variable inside generated template

I am generating an angularJS project with yeoman. I call the generator with an argument and I get it from my main generator's script (index.js) by doing:
this.argument('name', { type: String });
I can use this parameter inside this same index.js by using:
this.options.name
Question: I want to use this same this.options.name inside my template, so that i can give its value to a variable. How can I do it?
To access a yeoman variable from Node.js, I did the following:
I renamed the file connections.js from sails, renamed it to _connections.js and placed it at the same level than sails folder inside the folder "templates" from yeoman's generator. Leaving it like this:
> yeomanGeneratorFolder
> |-app
> |-index.js
> |-templates
> |-sails
> |-_connections.js
> |- ....
On the Generator's index.js. I created a function to write on a js file the data I needed. I sent a JSON object inside the copyTpl() function which contains the data I will need in the new file:
connections() {
this.fs.copyTpl(this.templatePath('_connections.js'), this.destinationPath('./config/connections.js'),
{
dbName: this.item.dbName
});
}
In _connections.js I wrote:
database: '<%=dbName%>' //optional
Notice dbName is the key I gave to the JSON I sent inside the copyTpl() function in index.js.
Define an angular constant and set it to this value. Then inside the controller associated to this view, just inject this constant.
myApp.constant('YEOMAN_NAME', MYVALUE);
Then just inject your constant inside the controller associated to your view, associate this constant to a scope variable and use it inside your template.
Now the "hardest" part is how to get this value inside the angular environment.
I don't know what is your index.js, I suppose that is only the main script associated to your page.
In this case, if you do inside the main script something like
this.myVariable = 'myValue';
You are actually creating a new attribute to the window object (if you are not doing that inside some function)
So what you could do is to associate this variable to a window parameter, and try to be most specific as possible so you are not on risk to override something else in the window, like:
window.myYeomanName = this.options.name;
Then you can define your constant inside angular everywhere just doing:
myApp.constant('YEOMAN_NAME', window.myYeomanName);

How to transfer a object from JS to AngularJS?

I got an JS-object in my index.html namend user. In this object are some user with mail, name etc.
So now I want to use this object in my app.js (AngularJS). I need it there.
I tried to tranfer it like this in my app.js:
var tempArr = $scope.user;
But it does not work.
Is there a possibility to transfer it from JS in my index.html to app.js?
As You asked From JS to angularjs so anything that is in js is in global window scope of browser and accessible inside angularjs scope so no problem to use a variable from js to angularjs context.
In your, app.js you probably have something like
var app = angular.module(/*blah blah*/);
That same app variable should be (made) accessible from the outside i.e. in the global scope. That way you can just write
app.tempArr = $scope.user;
But, of course, this is just quick and dirty solution. What I usually do is to create one global object, like
var GLOBAL = {};
and attach everything of mine on it, like
GLOBAL.app = angular.module(/*blah blah*/);
GLOBAL.someHelperFunction = function someHelperFunction(){};
and even, if needed
GLOBAL.tempArr = $scope.user;
// even better if you just clone the user values
// not just attach it to GLOBAL

In a Node app with express JS, how can I include and run a separate JS file?

I have a javascript file that contains some functions that grab an RSS feed and save the contents in a database. I originally had it being called by the HTML page, but I want this file to instead be running in the back-end all the time (grabbing updates from the RSS feed and saving it to a database).
My question is, how can I attach and run this separate javascript within my app? I assume it will look like this:
In app.js:
var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.SomeFunction();
This isn't working though. Also, would variables declared in my app.js be available in RSSReader.js?
Thanks.
how can I attach and run this separate javascript within my app?
The app.js code you show should work just fine. The key is that you have to make your RSSReader.js file into a module that exports the functions it wants to be public:
So, inside of RSSReader.js, you would have something like this:
module.exports = {
someFunction: function() {
// code here
},
someOtherFunction: function() {
// code here
}
};
Then, in your other file, you can load that module and use it like you had:
var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.someFunction();
RssReader.someOtherFunction();
node.js documentation for modules is here.
Also, would variables declared in my app.js be available in
RSSReader.js?
No, they would not unless you explicitly declared the app.js variables as properties on the global object. The usual node.js convention for sharing from app.js to another module is that you create an initializer method for the RSSReader.js module (you can call it init) and you pass it any context it needs (usually an object with some properties on it) from app.js and the RSSReader.js module can then store that context for its use.
So, if you want to share some variables from app.js to RSSReader.js, you could share them via a .init() method like this:
RSSReader.js
var data;
module.exports = {
init: function(options) {
data = options;
},
someFunction: function() {
// code here can access the data variable
},
someOtherFunction: function() {
// code here can access the data variable
}
};
app.js
var RSSReader = require('./public/javascripts/RSSReader.js');
RSSReader.init({express: express, db: db});
RSSReader.someFunction();
RssReader.someOtherFunction();

Categories