Access Functions Between Two External Javascript Files - javascript

I have a pretty JavaScript-heavy site that I'm working on, so to try and keep the code a little more under control, I tried to group my code into several logical external JavaScript files (.js files). For the most part it works just fine, but for some reason one function located in the file viewer.js file does not like being called from the ajax.js file (in other words, it's not - the Firebug console tells me nb_displayError is not defined (where the function in question is nb_displayError().
I tried placing the viewer.js script tag both above and below my ajax.js script tag in my HTML file, but neither seemed to make a difference. Strangely, I can call functions in my ajax.js file from another JavaScript file but this one in particular fails. Any thoughts as to why?
In case it's useful to you, the function calling creating this issue is defined as the following (I don't think it's anything particularly tricky):
function populateZoomLevel() {
var model = $('#modtype').children(':selected').text();
var lat = $("#loc-label").data('location').latitude;
var lon = $("#loc-label").data('location').longitude;
$.get("checkDomains.php", { result: 'zoomlevel', lat: lat, lon: lon, model: model })
.done(function(responseText){
if(responseText.substring(0, 7) == "error: "){ // Error flag
nb_displayError(responseText);
return; // Don't do anything further
}
$('#zoomlevel').html(responseText);
});
}

Related

How to call a function with in same java script file

I am writing Automation scripts using protractor. I have created a java script file in which I have created a function.
PlatformviewCnOPage is my JS file and searchCapabilityOfferingsName is function. I want to call this function in another function (in same file).
var PlatformviewCnOPage = function() {
this.searchCapabilityOfferingsName = function(){
coreutil.clickElement(objectrepo.platformView_Searchbox_EnterBtn,'xpath');
browser.sleep(2000);
var searchResult= coreutil.getTextofElement(objectrepo.platformView_SearchResult,'xpath');
return searchResult;
}
I want to use the above function i.e searchCapabilityOfferingsName in another function in same java script file. I have tried some combinations but its not working.Basically I am new to java script.
this.verifySearchinCnO = function(){
this.searchCapabilityOfferingsName();// Failed-method not defined
searchCapabilityOfferingsName(); //Failed method not defined
Create object of same file and call the function. // Failed.
}
};
module.exports = PlatformviewCnOPage;
Could anyone suggest how can I call the function in another function in same JS file?
PlatformviewCnOPage is defined as object/function which contains the method searchCapabilityOfferingsName.
So you can easily call PlatformviewCnOPage.searchCapabilityOfferingsName()
There should be some mistake in your PlatformviewCnOPage.js which lead to some definitions missing even loaded by require.
You can try below steps to figure out the wrong place:
Step 1 comment out other codes only except function: verifySearchinCnO and searchCapabilityOfferingsName
Step 2 add a console.log(xxx) as first line of the function: verifySearchinCnO and searchCapabilityOfferingsName
Step 3 run your test script again, if the both console.log(xxx) print out, means the wrong place in functions you commented out, then remove comment of some code lines and run test script again until find the correct place.

Moving created files with JXA

I'm new to JXA scripting, but I'm attempting to troubleshoot some older scripts currently in place here at work. They loop through an InDesign document and create several PDFs based on it. Previously, they would be stored in a folder called "~/PDFExports". However, this doesn't work with 10.10.
If I change the code to just place the PDFs in "~/", it works fine. From there, I'd like to move the files to "~/PDFExports", but I can't seem to find an answer on how to do that. I've seen things about making calls to ObjC, or to call Application('Finder'), but neither work - they both return undefined.
Am I just missing something basic here, or is it really this hard to simply move a file with JXA?
EDIT: Some syntax for how I'm creating the folder in question and how I'm attempting to work with Finder.
//This is called in the Main function of the script, on first run.
var exportFolder = new Folder(exportPath);
if(!exportFolder.exists) {
exportFolder.create();
}
//This is called right after the PDF is created. file is a reference to the
actual PDF file, and destination is a file path string.
function MoveFile(file,destination){
var Finder = Application("Finder");
Application('Finder').move(sourceFile, { to: destinationFolder });
alert("File moved");
}
Adobe apps have long included their own embedded JS interpreter, JS API, and .jsx filename extension. It has nothing to do with JXA, and is not compatible with it.
InDesign's JSX documentation:
http://www.adobe.com/devnet/indesign/documentation.html#idscripting
(BTW, I'd also strongly advise against using JXA for Adobe app automation as it has a lot of missing/broken features and application compatibility problems, and really isn't fit for production work.)
Here's the link to Adobe's InDesign Scripting forum, which is the best place to get help with JSX:
https://forums.adobe.com/community/indesign/indesign_scripting
You could use Cocoa to create the folder
var exportFolder = $.NSHomeDirectory().stringByAppendingPathComponent("PDFExports")
var fileManager = $.NSFileManager.defaultManager
var folderExists = fileManager.fileExistsAtPath(exportFolder)
if (!folderExists) {
fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(exportFolder, false, $(), $())
}
and to move a file
var success = fileManager.moveItemAtPathToPathError(sourceFile, destinationLocation, $());
if (success) alert("File moved");
Consider that destinationLocation must be the full path including the file name
and both sourceFile and destinationLocation must be NSString objects like exportFolder
Could it be that the folder is missing ? Could be your reference to the folder object not valid ? Any syntax to show ?
I will share some of what I learned about JXA move and duplicate methods. I am not a professional programmer just an attorney that is passionate about automation. My comments come from much trial and error, reading whatever I could find online, and A LOT of struggle. The move method does not work well with Finder. Use the System Events move method instead. The duplicate method in Finder works just fine. The duplicate method does not work well in system events. This is a modified snippet from a script I wrote showing move() using System Events.
(() => {
const strPathTargetFile = '/Users/bretfarve/Documents/MyFolderA/myFile.txt';
const strPathFolder = '/Users/bretfarve/Documents/MyFolderB/';
/* System Events Objects */
const SysEvents = Application('System Events');
const objPathFolder = SysEvents.aliases[strPathFolder];
SysEvents.move(SysEvents.aliases.byName(strPathTargetFile), {to: objPathFolder});
})();

Include a javascript file only once in Joomla

now, this question has been asked and answered successfully many times, yet none of the things i try work.
I have tried head.js & require.js libraries
I have also tried
if (!window.unique_name) {
unique_name = true;
//code here..
}
none of which I can get to work (the global variable is always undefined)
the script I am trying to include runs something like this:
//clock.js
clockyTick = function() {
//my code here
}
setInterval(clockyTick, 1000);
the apps that call this script, standalone, work fine.
only when both apps are included on the same page (via calls to PHP require()) they break.
Here is the cause of the problems (I think):
I am building custom web apps on a (Joomla) site and have the requirement of displaying two of my apps on the same page.
Both apps need the same .js file to operate correctly, which works fine when they run standalone, but as soon as both apps are running on the same page (in the admin section) the scripts conflict and stop each other from working
(the script in question is a dynamic clock script that grabs the specialised contents of a div and modifies it to something else)
I think the reason I cannot get aforementioned libraries to work, is the fact that they also are being included twice on the admin page.
is there any way around this, or do I have to bite the bullet and integrate a library into the main Joomla template? (meaning the library is uselessly loaded on every single page, yet only used on 3 of hundreds)
jQuery is also required, separately, on each app..but thankfully I am able to use noConflict to avoid problems there (not ideal)
The joomla way would be to instantiate the document inside your module and unset only the conflicting script as described in this question here just before you load the module's script:
1) get an instance if the document object and remove the js files (you
could do that in a plugin) :
<?php
//get the array containing all the script declarations
$document = JFactory::getDocument();
$headData = $document->getHeadData();
$scripts = $headData['scripts'];
//remove your script, i.e. mootools
unset($scripts['/media/system/js/mootools-core.js']);
unset($scripts['/media/system/js/mootools-more.js']);
$headData['scripts'] = $scripts;
$document->setHeadData($headData);
?>
Or in your case, I think you could try the dirty solution below inside your js files:
//1st module script
var unique_name;
if (unique_name == false || unique_name == null) {
unique_name = true;
//code here..
alert("Included 1st script");
}else{
//do nothing
alert("Not included 1st script")
}
//2nd module script
var unique_name;
if (unique_name == false || unique_name == null) {
unique_name = true;
//code here..
alert("Included 2nd script");
}else{
//do nothing
alert("Not included 2nd script")
}
Here is a DEMO
If you are having conflicts with PHP require(), you can try require_once(). However, as mentioned, that’s not the Joomla way of doing things.

How to get name of JavaScript file being executed?

I'm working on a project that contains several features, so I'm trying to organize each feature on a separated JavaScript file in such a way that the code can be loaded on demand. I want to standardize the load and execution process so I'm trying to develop a function that can load and execute the JavaScript file if it is not present in memory or just execute it if it is already loaded. One approach would be to make the function to require two parameters, the file name and the name of entry point function, then check if the script is already loaded, if it is just execute the entry point function, or if it is not, then load the script and upon the onload event execute the entry point function, this approach works fine but it requires the main module to know all the entry point function names, which in the future may become a pain in the neck, as a careless programmer may inadvertently duplicate a function name. A much cleaner and safer approach would be to name "main" all the entry point functions, and upon first execution associate that "main" to its script DOM object... more or less like this:
Loaded module:
function(){
function main(){
.
. some code here
.
}
Install(getThisFileName(),main);
}();
Main module:
function Load(fn){
var el,ff,i
el = document.getElementsByTagName("script");
ff = "http://"+window.location.host+fn;
for(i=el.length-1;i>=0;i--){
if(el[i] && el[i].src==ff){
el[i].Main();
return;
}
}
el = document.createElement("script");
el.type = "text/javascript";
el.src = ff;
}
function Install(ff,ep){
var el,i;
el = document.getElementsByTagName("script");
for(i=el.length-1;i>=0;i--){
if(el[i] && el[i].src==ff){
el[i].Main = ep;
ep();
return;
}
}
}
But in order to do so I need to know the name of the JavaScript file being executed, which I don't know if it is even possible. Any Ideas?
The easiest way might be to have included first:
var currentFile;
function getThisFileName() {
return currentFile;
}
And at the beginning of each file at the top simply do:
currentFile = 'thisFileName.js';
This will only work however if your code is executed sequentially, once all the files are loaded currentFile will always be the name of the last file.
And alternative method would be to set currentFile at the start of each function in each file. So while that specific function is being accessed you can call your getThisFileName() and it will tell you the last file run, or the current file being run.
Unfortunately this has a bit of overhead with your code itself.
The following will give you all the scripts as an array.
var allScripts = document.getElementsByTagName("script");
The current file will always be the last one .. so allScripts[allScripts.length-1] will give you the current javascript file. You can access the src attribute from this.
EDIT:
This won't work for asynchronous implementation.
You could globally declare an object like:
var scripts = {
addScript : function(filename) {
scripts[filename] = {
loaded : true,
executed : false
}
}
}
Then at the very bottom of each file call:
scripts.addScript('myFilename.js');
Then at the end of the script's execution call:
scripts['myFilename.js'].executed = true;
Then at any time you can check scripts to see if a particular file is loaded/executed.

JSON callback doesn't trigger if function called from within own file

The title is the best way I could sum it up. It's a little fuzzy on how to explain this.
Basically, if I include the javascript file holding the JSON function from within an html file, then trigger the JSON function - callback works. However, if I just call the JSON function from within it's own file - callback never fires. Not sure if this is some sort of javascript or web browser security feature. Would be greatful for an explanation.
Here are some examples.
Working version:
json.html: (trimmed down)
<html>
<head><script type="text/javascript" src="json.js"></script></head>
<script>
JSON_Object(json_url, function(json_obj) {
alert(json_obj); // this version works!
});
</script>
<html>
json.js:
function JSON_Object(json_url, callback) {
// This function will return an object to the JSON data.
json_url = json_url + "&callback=jsonCallback";
var json_script = document.createElement("script");
json_script.setAttribute("src", json_url);
json_script.setAttribute("type", "text/javascript");
window.jsonCallback = function(jsonObjReturn) {
// cleanup
document.body.removeChild(json_script);
delete window[callback];
callback(jsonObjReturn); // use our callback function to return the data.
}
document.body.appendChild(json_script);
}
Non-Working version - Another function inside json.js:
JSON_Object(content_page, function(json_obj) {
alert(json_obj); // This version doesn't work. Never called.
});
After a bit of research, I found that I was right. It IS a web browser security feature for extensions.
From the following link:
http://code.google.com/chrome/extensions/content_scripts.html
Quote from the page
However, content scripts have some limitations. They cannot:
Use variables or functions defined by their extension's pages
Use variables or functions defined by web pages or by other content scripts
JSON falls into the above categories because it uses a function for it's callback.

Categories

Resources