I am trying to create a chart using highcharts in which i am not able to fetch data which i store in another js file.
My main.js file has all the code for creating chart. It has the section of series.
series: [{
name: 'Desktops',
data: '/data/desktop.js',
tooltip: {
valueDecimals: 2
}
}]
Here i want to refer data from another js file. The name of file is desktop.js and it has just the below array
var desktopData = [[1475272800000, 117759], [1475359200000, 106147], [1475445600000, 147747], [1475532000000, 302031], [1475618400000, 520539], [1475704800000, 245353], [1475791200000, 180376], [1475877600000, 78819], [1475964000000, 90466], [1476050400000, 257822], [1476136800000, 284465], [1476223200000, 242898], [1476309600000, 297186], [1476396000000, 268069], [1476482400000, 183149], [1476568800000, 410442], [1476655200000, 1117798], [1476741600000, 1274668], [1476828000000, 1331799], [1476914400000, 1230213], [1477000800000, 888251], [1477087200000, 572050], [1477173600000, 931144], [1477260000000, 1556641], [1477346400000, 1526736], [1477432800000, 1310133], [1477519200000, 1207422], [1477605600000, 785556], [1477692000000, 487264], [1477778400000, 787714], [1477868400000, 942663]];
How can i refer array defined in another file?
Do you use any type of the framework? To load JS file in another file, you need to require it somehow, either by using AMD, ES imports or any other way (be it synchronous or asynchronous).
If you are just adding the files to the HTML (using script tags), then the only thing you have to do is to make sure that the files are loaded (DOMContentLoaded event) and then, you have to attach the data to a global scope.
Global scope in the browsers is called a window and every time when you use variable that was not declared in your scope by var it means that the JS is searching for it in the global scope. In order to assign something to a global scope you can just omit var or explicitely assign it like this:
window.desktopData = [];
// And then in another file, assuming that the data is ready
var myData = window.desktopData
Please also remember that including files in <script> tags usually means that they will block your browser and the order of the files matters (at least when you want to rely on the fact of one file already loaded before another file). I'd suggest using some kind of import system then:
http://requirejs.org/docs/whyamd.html
Related
Say I have a website with a file structure like this:
index.html
main.js
modules/my-module.js
index.html contains (along with a lot of HTML):
<button id='my-btn'>My Button</button>
<script type='module' src='./main.js'></script>
main.js contains:
import { myBtn } from "./modules/my-module.js";
and modules/my-module.js contains:
const myBtn = document.querySelector("#my-btn");
myBtn.addEventListener("click", function(){
alert("Hallo from My Button");
});
export { myBtn };
Now if I click on the button I get an alert as expected.
The problem I am having is that I have some information (ie variables with values such as strings, arrays etc) in other script tags on the index.html page which I need in modules/my-module.js
I do not want to use a global variable for this because they are evil.
I thought of creating an element(s) on the index.html page with data set attributes as keys and assign values to them. The element could then be accessed from modules/my-module.js and its data set attributes would be readable. This does work when I try it but it seems a long winded way of getting access to information available on the index.html page.
It has been suggested I create a class or function returned by the module and pass data into it. The problem with that, to me, is that I am trying to keep code related to the same thing all together in the same module. If I have to pass functions out of the module to be invoked with extra data then my code base is less well organised.
Is there any other approach which would be more direct?
Is there some sort of Session-like variable to hold an array in Nodejs?
What I meant is like something where I can define the name in other scope and be accessed in different scope (i.e: Variable("Array1") is defined in function A but accessed in function B and persists until it is destroyed).
The reason is I am using Meteor for slicing big files into small blobs and pass it back the chunk to the server. I tried to use the combination of fs.WriteFile and fs.AppendFile but somehow the file is mutilated along the way (the file is a video and playback error occurred with the copied file).
I read somewhere that blob can be rebuild by the constructor. However, I would need to pass this to a global or session-like variable in order to do so.
So...how can I use such thing in Nodejs?
There is such thing – it is called database :-)
When you're in Meteor, all files are loaded to a single running environment. Therefore, unlike in plain Node, a global variable created in one file can be accessed in any other one. So you can write
Slices = {};
in one file, and then in another say
Slices['Array1'] = ...
Notice there is no var keyword when defining the Slices object, otherwise it wouldn't be global but scoped to the file.
There is obviously one problem with the above method, and it's persistence over server reload. When the server crashes and restarts, or when you upload a new version, all such variables are recreated and you lose your data.
To prevent this, you need to store your variables in a place where they are retained permanently – a database of some kind. There are several solutions tailored for such runtime variables (such as Redis), but since you're using Meteor the natural solution would be to use the provided Mongo database. So just create a new collection on the server side
Slices = new Meteor.Collection('slices');
and use the usual find, insert, update and remove methods to access your variables.
If everything happens in the same process space, you can use a module as a singleton.
Remember, even if a module is included multiple times, the same copy is returned.
So if you have this module:
module.exports = new Array();
And you include it by several other modules, each one of them will have the same array instance.
You can also have a more complex singleton:
var blocks = {};
module.exports.addBlock = function(name, block) {
blocks[name] = block;
};
module.exports.getBlock = function(name) {
return blocks[name];
};
module.exports.delBlock = function(name) {
delete blocks[name];
};
module.exports.list = function() {
return Object.keys(blocks);
};
In your different files, you would include and use this module like:
var blocks = require('./blocks');
console.log(blocks.list());
Read about module caching here.
I'm having an issue with QML/JS integration.
I have a javascript list variable stored in a .js file. I want to write to this variable from one QML file, and read it from another QML file. I cannot seem to find a solution to this. I've over-simplified my actual code to make it comprehensible!
// writeValue.QML
import "../javascript/storedValue.js" as StoredValue
...
MouseArea{
onClicked{
StoredValue.value.push(1)
}
}
// readValue.QML
import "../javascript/storedValue.js" as StoredValue
...
Text{
text : StoredValue.value
}
//storedValue.js
var value = []
I have tried using '.pragma library' and not using it, to no avail.
What happens is the writeValue.QML writes successfully, so [1, 1, ,1, ...]. Whereas readValue.QML just finds an empty list, [].
Just put .pragma library at the beginning of the JS file. In this way, there will be only one instance imported by QML components.
Remember however that no update signal is issued when a var property changes. If you want to have global var with update support, you should export a custom QObject via setContextProperty() on the C++ side.
I'm using jQuery Mobile Ajax navigation feature, And I need to change a variable that is defined inside external js file, So I can't put my definition before I load that js file...
So, How to change value of a variable for external javascript file after the js file is defined?
(That external js file includes events)
So this question is not duplicate of that question.
Update
My JS File contains events, something like this: $(document).on('mousemove','#main',function() { /*something*/} );
And I need that variable. Is it possible to pass variable to that?
I have tried simply changing that variable i = 5;, but I'm getting undefined error.
Update 2
The external JS file is something for some pages that are almost same, but a little different, just one or two parameters.
And I simply want to pass the parameters to that JS file. Is it possible? How?
Let's assume http://www.example.com/external.js defines variable foo, which you want to change.
<script src="http://www.example.com/external.js"></script>
<script type="text/javascript">
foo = "my new value";
</script>
This assumes that external.js defined foo in the global scope. If it's defined in an anonymous function or similar, you won't be able to change the value.
Depending on what you're doing, you can just set the variable and it'll work. Example:
// JS file
blah = "Hello";
function doSomething() {
alert(blah);
}
// HTML file
blah = "I'm a fish";
doSomething(); // alerts "I'm a fish";
Alternatively, pass the variable as an argument to relevant functions instead of using global variables.
I need to send data in a HTML page to a script file that is loaded in that page. The simplest way i can think of is to use a global variable which is defined in the page and accessed in the script file.
We all know global state is bad, so i started thinking about the options available for passing data from HTML page to script file without using global state. I cant find (or think of) any.
I am curious whether this is possible. Any ideas?
It really depends what you're doing. In general, I wouldn't advise this methodology, but it's something to consider depending on your circumstances. For the sake of this example, I'll assume you're using jQuery (if not, replace the document.ready with whatever you want to use for onDOMReadyStateChange monitoring).
In the HTML:
<script type='text/json-data' id='some_data_set'>
{ 'foo': 'bar', 'baz': 1 }
</script>
In the JavaScript:
$(function() {
var myData = JSON.parse($('script#some_data_set').html());
// YOUR CODE GOES HERE
});
Nope. All the javascript scope starts from a global level, therefore you must have at least one global reference to your data.
Let's say you wanted to store a list of products and events:
var myGlobalData = { "products":<products>, "events":<events> };
Where <products> and <events> are two different data blocks.
If you're paranoid on global objects, you can simply delete the reference point (thus it's contents) after you finished using it, as follows:
delete window.myGlobalData;
One option is to scope your data. For example, in JS file you can define an object like:
var processor = {
function setData(o) { // do stuff
}
};
Then in your HTML you know that the data is scoped to the processor. So you can do something like:
processor.setData({someData});