javascript run function with adobe air - javascript

I am working on the adobe air with javascript and html. I want to run multiple functions in a function with show the percentange run on the each function but the percentage also show the last calculation please help me.
Edit: added code snippet from comment, but I may have butchered the layout.
function show_percentage() {
down_admin()
down_staff()
down_client() }
function down_admin() {
down all information of admin from the server; flag=1; }
function down_staff() {
down all information of the staff falg=2; }
we want to calculation show the every after loaded functions. as percentage=25% to 100%

If you downloading several types of info and want to show summary progress, first you need to know bytes total of each download. When you get ProgressEvent from each operation, you may call function show():
function show() {
var progress = (adminBytesLoaded + staffBytesLoaded + clientBytesLoaded) * 100 /
(adminBytesTotal + staffBytesTotal + clientBytesTotal);
//show progress somehow
}
Update: some clarifications
Load resource you need with Loader. Add event listener to ProgressEvent on Loader.contentLoaderInfo. There will be three listeners for three load operations - load admin data, client data and staff data. When you get progress event from each operation (track it with three vars), you will know download size total:
var adminTotal:int;
var clientTotal:int;
var staffTotal:int;
var adminLoaded:int;
var clientLoaded:int;
var staffLoaded:int;
function onAdminLoadProgress(event:ProgressEvent):void
{
adminLoaded = event.bytesLoaded;
adminTotal = event.bytesTotal;
//if other operations already going, show progress
if (clientTotal && staffTotal)
{
showProgress();
}
}
function onClientLoadProgress(event:ProgressEvent):void
{
clientLoaded = event.bytesLoaded;
clientTotal = event.bytesTotal;
if (adminTotal && staffTotal)
{
showProgress();
}
}
//write onStaffLoaded yourself as an exercise :)))
I'm assuming you will make single request for each of those three downloads.

Related

How to create onclick events for video embedded using the Flowplayer javascript API?

My aim is to add buttons below my player that jump to specific moments in the video.
There's a demo example that does basically what I want:
https://flowplayer.com/demos/using-the-api — however it is based on the cloud player implementation of Flowplayer, and I'm using the Javascript API to embed my player. The basic relevant script is this:
flowplayer.cloud.then(function () {
var api = flowplayer("#player")
seek3.onclick = function() {
api.fas.seek_to('00:01:01:11');
}
});
An example I found of creating buttons using the Javascript API is as follows:
flowplayer(function(opts, root, api) {
// small jQuery-compatible utility built inside the player
var $ = flowplayer.mq;
// render a custom button when the player is mounted
api.on('mount', function() {
var btn = $('<button>').txt('Test Button').on('click', function() {
api.toggleMute();
});
$('.fp-controls', root).append(btn);
});
});
That works fine with my player. When I try to merge the two approaches, though, I fail. Here is the broken code:
flowplayer(function(opts, root, api) {
var api = flowplayer("#flowplayer");
seek3.onclick = function() {
api.fas.seek_to('00:01:01:11');
}
});
I tried also as alternatives
document.getElementById('seek3').onclick = function()
And
$('#seek1').onclick = function() {
(preceded by the additional line of code borrowed from the working example):
var $ = flowplayer.mq;
but with every variation I keep getting the following error: "Uncaught TypeError: Cannot set property 'onclick' of null".
Any help would be much appreciated. I've found the Flowplayer documentation really difficult to use, since in search results it's often hard to even tell which version of the player is being referenced. I would really like to find some basic info about interacting with the API in addition to solving this particular problem.
For anyone else who might be having difficulties interacting with the API, Flowplayer kindly posted a new demo example -- with similar functionality as in the cloudplayer demo, but this one for the javascript player: https://codepen.io/team/flowplayer/pen/KOzWOK
var api = flowplayer("#player",
{ src : "//edge.flowplayer.org/drive.m3u8"
, autoplay : false
, token : "eyJraWQiOiJqOEF6djg5NlJMMWIiLCJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJjIjoie1wiYWNsXCI6NixcImlkXCI6XCJqOEF6djg5NlJMMWJcIixcImRvbWFpblwiOltcIm5ncm9rLmlvXCJdfSIsImlzcyI6IkZsb3dwbGF5ZXIifQ.UtJliSh4IcIKs71PVzXWdIrJJ8-1_KRK0hKd7OKp5EJhAdpZStuYbbU4bgDs--C6Gak6OBrb-xQBh6sd4dyrlA"
, muted : true
})
/**
* helper function to seek if possible or
* tell the player to seek when possible
*
* btn {HTMLElement}
* seconds {Number}
*/
function chapter (btn, seconds) {
btn.onclick = function () {
// player is preload=none so we must tell
// the player to seek when it is possible
if (api.readyState == 0) api.setOpts({start_time: seconds})
// player has already started loading content
if (api.readyState > 0) api.currentTime = seconds
// attempt to play content
api.togglePlay(true)
}
}
// bind the buttons to times
chapter(seek1, 20)
chapter(seek2, 45)
chapter(seek3, 60)
My working version includes the following variations on the JS code:
/**
* helper function to seek if possible or
* tell the player to seek when possible
*
* seconds {Number}
*/
function seek_to_cue (seconds) {
//alert('bingo?'); //tft
// player is preload=none so we must tell the player to seek when it is possible
if (api.readyState == 0) {
api.setOpts({start_time: seconds});
}
// player has already started loading content
if (api.readyState > 0) {
api.currentTime = seconds;
}
// attempt to play content
api.togglePlay(true);
}
and in my PHP code which includes the JS player call:
$button_actions .= 'document.getElementById("'.$button_id.'").addEventListener("click", function(){ seek_to_cue('.$start_time_seconds.'); });';

Nightwatch 'For' Loop not executing commands

I'm trying to create a loop within nightwatch.js that will;
load a page
assert an element
click on this element
for a selection of pages.
Below is my code;
var carTypeHref = ['/type-hatchback/','/type-saloon/','/type-estate/','/type-4x4/']
var listCarTypeHref = carTypeHref[Symbol.iterator]();
module.exports = {
'navigate to small car type cfs landing page': function (browser) {
browser
.url(browser.launch_url + browser.globals.carsForSale + '/type-small-city/')
.agreeCookiePolicy();
},
'navigate to car type cfs landing pages and check dealer link details': function (browser) {
for (let carType of browser.globals.listCarTypeHref) {
browser
.url(browser.launch_url + browser.globals.carsForSale + (carType))
.assert.elementPresent('.for-sale-result-item__dealer')
.click('.for-sale-result-item__dealer')
}
},
'closing the browser': function (browser) {
browser
.browserEnd();
},
};
The urls load correctly, one by one as defined in carTypeHref and listCarTypeHref.
However, the rest of the commands within this loop don't appear to be executed;
.assert.elementPresent('.for-sale-result-item__dealer')
or
.click('.for-sale-result-item__dealer')
are not executed.
I'm a bit stuck as to why, so any help would be appreciated.
Thanks.

Speed up multiquery with Instagram api

I'm getting the images with the media/search endopoint passing a lat and lon like this
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
and then I'm gettin only the pics with a certain tag #instabeachpro,if the pic is not found I go trough the next set of pics adding the last pic created_time to the url with the max_timestamp parameter, here is the code I'm using
(function(){
var url,tags,menos,photos = new Array(),i=90;
function search(){
generateResource(tag;
$.getJSON(url, toScreen);
}
function init(){
bindEventHandlers();
}
function generateResource(){
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
return url;
}
function toScreen(){
var next_url=url+"&max_timestamp="+data.data[data.data.length - 1].created_time;
$.each(data.data, function(index, photo){
i--;
tags=photo.tags;
menos=jQuery.inArray( "instabeachpro", tags );
if(menos!=-1)
{
$('div#photos-wrap').append("<div id='"+i+"' ><a href='"+photo.link+"'><img src='"+photo.images.low_resolution.url+"'/></a></div><div><img class='second' src='"+photo.user.profile_picture+"'/></div>");
}
else{
i++;
}
});
if(next_url!=undefined+"&callback=?" && i>=0){
console.log(i);
pagination(next_url);
}
}
function pagination(url)
{
$.getJSON(url, toScreen);
}
Instagram.App = {
search: search,
init: init
};
function bindEventHandlers(){
$('body').on('click', '#loadObject', function(){
url=$(this).attr('data-next-url');
i=90;
if(url=='undefined')
{
alert("undefined");
}
else{
pagination(url);
return false;
}
});
}
}());
$(function(){
Instagram.App.init();
Instagram.App.search();
});
This works but it's extremely slow and I have no idea what to do to speed it up, because the api doesn't support searching like I want to do, and i need to get al the pcitures with a certain tag IN a certain location, I have been told a number of times this is the only way to do it, but there has to be a faster way.Thank you.
Your method is extremely inefficient, since the tag you are searching is not popular and very small percentage of people use it, so getting API around location and then filtering by tag is expensive on number of API calls.
Search the other way round, make API call for the tag and then check for location for that photo. Check this implementation: http://www.gramfeed.com/instagram/tags#instabeachpro
You can get the tag photos and maps it on Google Maps, scroll to load more photos and see that very few of the #instabeachpro photos are tagged with location

How to show a wait message OR loading image when a write operation is being performed using spapi_lists.js library.?

I am using SPAPI_Lists.js and SPAPI_Core.js libraries to update/add records to share point 2007 lists.
i want to show a wait message OR loading image still the write or read operation is completed.
Please suggest me how this can be done.
here is the code
var list = new SPAPI_Lists("ListURL");
var newItem = {
Title: "News",
Link: "LinkURL"
};
var items = list.quickAddListItem("List ID", newItem);
As the above code indicates, i want to show a wait message OR loading icon still the quickAddListItem is completed
Thanks in advance.
Mmhhhh ... Do you have any documentation about these libraries ? If quickAddListItem is not asynchronous, then you cannot do what you're trying to achieve.
Or you can try showing your loading image first, and then call setTimeout:
$('.my_loading_img').show();
// 500 means to wait 500ms before doing the adding... you can try a smaller number
setTimeout(function() {
var list = new SPAPI_Lists("ListURL");
var newItem = {
Title: "News",
Link: "LinkURL"
};
var items = list.quickAddListItem("List ID", newItem);
}, 500);
Otherwise, I created a JS library that deals with Sharepoint webservices : http://aymkdn.github.io/SharepointPlus/
With my library and your example:
// show your loading image
$('.my_loading_img').show(); // jquery
// call SharepointPlus
$SP().list("ListName").add({Title:"News",Link:"LinkURL"},
{
error:function(items) {
alert("Error when adding the item");
$('.my_loading_img').hide(); // hide the image
},
success:function(items) {
alert("Item added!");
$('.my_loading_img').hide(); // hide the image
}
}
);

display message javascript while a calculation is being made

I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.

Categories