call back function after file read in Phonegap - javascript

I am dealing with this problem from quite a while, please suggest me a solution:
For android app development, I am using phonegap framework.
I have a async function readFromFile() which reads the json file (which is updated using a user data everytime) stored in SD card, and stores the text result into the global variable, Next I have a function populatePageContents() which reads the global variable, and populates the page's html from the json data.
I want the populatePageContents() function to be called after readFromFile() function has finished reading the file data into global variable.
I tried using someting like this:
<script type="text/javascript">
globalVariable = '';
readFromFile(); // Uses phonegap's file API to read file and puts result into global variable
setTimeout(function() { populatePageContents(JSON.parse(globalVariable)); } , 500);
</script>
The above method works sometimes, but not always. Please suggest some better use of callback functions. Thanks!

Please use callbacks for making it work everytime
U can use something like this:
readFromFile(function(data){
populatePageContents(JSON.parse(data));
});
And your readFromFile function should look like this :
readFromFile(callback){
/***read file phonegap code***//
callback();
}

Related

Javascript Moodle

Hi I am fairly new to moodle. I have been trying to test if my Javascript runs but to no avail. Here is what I have:
In /videojs/amd/src I made a test.js file with a simple command
define(['jquery'], function() {
return {
init: function() {
// Put whatever you like here. $ is available
// to you as normal.
alert("It changed!!");
}
};
});
Then I grunt the file and everything succeed, and made minified. But when I go to the page it doesn't run. Now I read Moodle's Javascript Doc and I see it says
The idea here is that we will run the 'init' function from our (PHP) code to set things up. This is called from PHP like this...
Where do I call this PHP?
Somewhere in the page you are outputting, you need to add a call like this:
$PAGE->requires->js_call_amd('PLUGINTYPE_videojs/test', 'init);
It's not entirely clear from your example what sort of plugin you are creating, so whichever type you are creating (https://docs.moodle.org/dev/Plugin_types), you need to put it in the appropriate subdirectory for your site (e.g. /mod/videojs, /local/videojs, etc.), then add some sort of PHP script as the entry point for your plugin and call the js_call_amd function from there.

How to redirect to a play framework url from within javascript without hard-coding the url

I need to do something seemingly quite simple.
In the same way that I can, from my scala.html file, create a link to another url, /entry, I need to do that from a javascript file.
i.e., from the scala.html:
<div class="footer">
<a href='#routes.Application.index()'>Home</a>
</div>
from my javascript event:
function() myEvent {
window.location="#routes.Application.entry()"; // DOESN'T WORK!
}
For routing from javascript, I've already had to setup my javascript routes for some ajax work I've already had to do.
My ajax work was calling a method 'findPersons()' so in my Application.java file, I had already:
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter( "appRoutes",
routes.javascript.Application.findPersons()));
}
Because I want to be able to redirect to my GET entry() method, I modified it to look like this:
public Result jsRoutes()
{
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter( "appRoutes",
routes.javascript.Application.findPersons(),
routes.javascript.Application.entry()));
}
Additionally I have these in my routes file:
GET /entry controllers.Application.entry()
POST /findPersons controllers.Application.findPersons()
When I am invoking my findPersons method, it is really nice and simple.
It looks like this:
appRoutes.controllers.Application.findPersons().ajax({
data: {
personIdentifier : personIdentifier,
surname : surname,
givenNames : givenNames
},
success : processDBQuery
});
For my simple redirect, I would like to be able to maintain the same loose coupling between my html/javascript code and the urls, as I can the ajax call above.
My redirect needs to occur on an event. Therefore, the easiest and quickest solution would have been simple to write:
function() myEvent {
window.location="/entry";
}
However, then I would be hard-coding the URL (which I have managed to avoid for my ajax call above), no longer maintaining that loose coupling I would so much like to have.
However, I see no examples in the documentation, and from what I have in the generated javascript (for my routes) there is no chance.
Is there any way to achieve what I am after?
thanks for reading!
p.s., I should add; I guess I have also thought of the possibility of using the ajax call that is generated, I guess I can probably fetch the page I want... and there is probably a means of replacing the current document with the entire content of the fetched page. but that just sounds bad.... wrong...
or not?
I was rather hoping for a substitution, as is done in my html
i.e, my link as shown above is generated to look like this:
<div class="footer">
<a href='/'>Home</a>
</div>
In the same way, I hoped there was some means of substitution in the javascript, so that the event function above ends up in being massaged into looking like this:
function() myEvent {
window.location="/entry";
}
Jacques, from the above comments, helped me to realize a work-around.
From within my "assets located" javascript file, I can still refer to page/template located javascript.
Own-file/assets located javascript doesn't seem to be transformed how I expected.
However, Page/template located javascript is transformed exactly how I require.
I can refer to a template located javascript function from my assets located javascript.
This means, I have a little work-around of one extra little function inside the template which does the redirection for me.
i.e.,
myJavascript.js:
function personResultsListClickHandler(personId) {
var fpersonId = personId;
return function() {
window.alert("hello! " + fpersonId);
affectRedirect();
};
}
myTemplate.scala.html
#main("person lookup") {
<script type="text/javascript">
function affectRedirect(){
window.location="#routes.Application.entry()";
} // Need this here so it will be transformed.
// asset located javascript doesn't seem to get transformed like javascript here in template! :(...
</script>
Another possibility is the fact that the Javascript object retrieved by calling:
appRoutes.controllers.Application.entry()
contains a url member. This url member is exactly what I can use to assign to window.location. However, it looks a bit unofficial.. in terms of
1. the member not being documented
2. not sure if the url member will exist in the future
3. the generated javascript is constructing an object dealing with ajax... and i'm just grabbing the URL member from it... it just feels... like a hack.
But i've tested this, and it works. See code below:
function patientResultsListClickHandler(personId) {
var fpersonId = personId;
return function() {
window.location=appRoutes.controllers.Application.entry(personId).url;
// window.location="/entry/" + fpersonId; // the sort of hard-coding of URL that
}; // I wanted to avoid, but don't seem able to.
}
Does anyone else have a better solution?

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.

jQuery page-flip animation

I am using a pageflip script called Moleskine Notebook. Inside the jquery.booklet.1.1.0.js file there is a function called next which turns the page. I want to call this function from my html file.
I tried "$mybook.next();" but it didn't work, I think I have to do something with jQuery.data() as it states on jquery.booklet.1.1.0.js file (lines 100-103)
//store data for api calls
b.data('booklet',true);
b.data('id', id);
b.data('total', src.children().length);
Here is the script:
http://tympanus.net/Tutorials/MoleskineNotebook/
Read the API docs:
$('#mybook').booklet('next');

How would I pass data to an external script loaded with $.getScript()?

So I'm trying to load a javascript remotely using jquery's $.getScript, but I'm puzzled on how I can pass data to the external script.
I've tried setting variables before the call but they aren't available in the script that gets loaded, and when I try to send/retrieve them using the query string, the remote script tries to read the querystring of the base file that it gets called from, not itself. Is there any other way to do this? Or is it possible to have a javascript file read its own querystring rather than the file it's called from (that's loaded in the browser)?
// editor ini
var editor_ini = { page: current_page, action: 'edit' };
var foo = 'bar';
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', function(){});
In the execute.js file, the editor_ini and foo are both unavailable, I get the same result with:
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', { page: current_page, action: 'edit', foo: 'bar' }, function(){});
because the remote script seems to be getting the query string from the original document rather than the one used when calling the file.
If it matters, I was trying to use the query object plugin for jquery for reading the query string.
global variable declared in inline javascript is accessible in external javascript page loaded using $.getScript().
I bet that your var foo='bar' is inside a function, so not visible in global scope. Try:
window.foo = 'bar'
Truly global variables will be accessible to your script. So, if they aren't, then it's probably because your variables that you think are global actually aren't. You can either move them to the top level scope or set them on the window object like Alexei suggested.
There are other ways to share data.
1) You can put an id on the <script> tag that loads the code and then have the code get the .src value from that tag and get the query string off the script's actual URL. I like this option, but I don't know if you can do it using jQuery.getScript() since I don't think it exposes that as an option.
2) You can have the loading script call a function that you provide and return an object with the desired data from that function.
3) Once the new script is loaded, you can call a setXXX() function in that script to set the state that it needs.
4) You can set information into a cookie that the other script can read.
5) You can encode data into a URL hash value that the other script can read.

Categories

Resources