Working on a script for InDesign I found this problem : if I call app.open() from inside button.onclick() it stops and nothing happens.
Since I'm a beginner with Javascript I'm probably doing something wrong. But if not, how do I fix? I can not find an alternative.
Please, only pure Javascript.
Thanks in advance.
Here the working code :
var book_info;
if (app.books.length != 1) {
var theFile = File.openDialog ("Select the book file to open...");
get_data(theFile);
alert(book_info.filePath + "\r" + book_info.name);
}
book_info.close();
function get_data(data) {
app.open(data);
book_info = app.activeBook;
alert("INSIDE FUNCTION" + book_info.filePath + "\r" + book_info.name);
return data;
}
and here the one not working :
var book_info;
var w1 = new Window ("dialog", "TEST");
w1.minimumSize.height = 50;
w1.minimumSize.width = 50;
var p1 = w1.add ("panel");
sel_button = p1.add ("button", undefined, "Select book");
var g1 = w1.add ("group");
g1.add("button", undefined, "Cancel");
g1.add("button", undefined, "OK");
sel_button.onClick = function(){
var theFile = File.openDialog ("Select the book file to open...");
get_data(theFile);
alert(book_info.filePath + "\r" + book_info.name);
book_info.close();
};
w1.show();
function get_data(data) {
app.open(data);
book_info = app.activeBook;
alert("INSIDE FUNCTION" + book_info.filePath + "\r" + book_info.name);
return data;
}
There is an alternative answer at app.open not responding if called from inside onclick()
It also suggested the use of 'palette' window instead of modal dialogue
Try this:
var book_info;
var theFile;
var getData;
var w1 = new Window ("dialog", "TEST");
w1.minimumSize.height = 50;
w1.minimumSize.width = 50;
var p1 = w1.add ("panel");
sel_button = p1.add ("button", undefined, "Open a book");
var g1 = w1.add ("group");
g1.add("button", undefined, "Cancel");
g1.add("button", undefined, "OK");
sel_button.onClick = function(){
theFile = File.openDialog ("Select the book file to open...");
getData =1;
w1.close(1);
};
w1.show()
if ( getData ==1) {
if ( theFile ) {
get_data(theFile);
}
}
function get_data(data) {
app.open(data);
book_info = app.activeBook;
alert("INSIDE FUNCTION" + book_info.filePath + "\r" + book_info.name);
return data;
}
Related
I have a problem on parse.com in which i to take the id of an type and pass it to another function which uploads an image. Then take the type.id among with the image and post it to another function which saves the data to a class.
This is what i've tried until now without success.
--OnClick code
$('#submitId').on("click", function(e, f) {
e.preventDefault();
typeSave(typeid1);
//var objnew1 = typeSave();
console.log("inside onclick " + type2);
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
//typeSave();
type2 = typeid1;
saveJobApp(parseFile, type2);
console.log("inside save onclick " + type2);
},
function(error) {
alert("error");
}
);
});
-- Type Code
var type;
var typeid1;
var type2;
function typeSave() {
var type = new Parse.Object("type");
var user = new Parse.Object("magazia");
//var bID = objbID;
//user.id = bID;
var cafebar = document.getElementById('cafe_bar').checked;
if (cafebar) {
var valueCafebar = true;
} else {
var valueCafebar = false;
}
var club = document.getElementById('club').checked;
if (club) {
var valueClub = true;
} else {
var valueClub = false;
}
var restaurant = document.getElementById('restaurant').checked;
if (restaurant) {
var valueRestaurant = true;
} else {
var valueRestaurant = false;
}
var pistes = document.getElementById('pistes').checked;
if (pistes) {
var valuePistes = true;
} else {
var valuePistes = false;
}
type.set("cafebar", valueCafebar);
type.set("club", valueClub);
type.set("restaurant", valueRestaurant);
type.set("pistes", valuePistes);
type.save(null, {
success: function(type) {
//saveJobApp(type.id);
var typeid1 = type.id;
console.log("inside type save " + typeid1);
//return ;
},
error: function(type, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
-- Send Data to parse.com class code
function saveJobApp(objParseFile, type2) {
var jobApplication = new Parse.Object("magazia");
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
var description = document.getElementById('description').value;
var website = document.getElementById('website').value;
var phone = document.getElementById('phone').value;
var address = document.getElementById('address').value;
var latlon = document.getElementById('latlon').value;
var area = document.getElementById('area').value;
var value = latlon;
value = value.replace(/[\(\)]/g, '').split(', ');
console.log("inside saveJobApp " + type2);
var x = parseFloat(value[0]);
var y = parseFloat(value[1]);
var point = new Parse.GeoPoint(x, y);
jobApplication.set("image", objParseFile);
jobApplication.set("email", email);
jobApplication.set("phone", phone);
jobApplication.set("address", address);
jobApplication.set("name", name);
jobApplication.set("website", website);
jobApplication.set("description", description);
jobApplication.set("area", area);
jobApplication.set("latlon", point);
jobApplication.set("typeID", type2);
jobApplication.save(null, {
success: function(gameScore) {
// typeSave(jobApplication.id);
},
error: function(gameScore, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
So resuming i am trying when i click the button to first run the typesave() function, after when it posts the type on the type class in parse, to take to type.id from the success function and send it to the parseFile.save().then
and then to send the objectFile and the type2 (which is the type.id) it in saveJobApp and them to save it in class magazia
What i get from the console.logs is this
Which means that my code post to the type class and takes the type.id
but it doesnt send it to the magazia class via the parsefile save.
Any idea of what am i missing?
I noticed your mistake is not about the functions but about trying to pass the type.id as a string and not as a function in the saveJobApp function.
if you try making it like this
function saveJobApp(objParseFile , objtype) {
var jobApplication = new Parse.Object("magazia");
var type = new Parse.Object("type");
type.id = objtype;
jobApplication.set("typeID", type);
I think it will work.
And also update the onclick and the ParseFile save code to this
$('#submitId').on("click", function(e) {
typeSave();
});
function PhotoUpload(objtype){
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
saveJobApp(parseFile, objtype);
},
function(error) {
alert("error");
}
);
}
And the success function in typeSave()
should be something like this
type.save(null, {
success: function(type) {
PhotoUpload(type.id);
},
Hope this helps :)
I want to show a loading icon while a task is being performed and then hide the icon after it has been performed. I need to use a web worker for the loading icon to show. The admin at This forum post said to use a web worker.
This is the code to execute in the web worker:
function getTheClients(xml) {
console.log(xml);
var client = xml.getElementsByTagName("WebClientList");
if(client.length === 0) {
$("#noClients" + platform).empty();
$("#noClients" + platform).append('<p style="margin-top:40px;margin-bottom:20px;text-align:center;">No clients at ' +
getSelectedDropDownOptionName("allVillagesDropDown") + ', ' +
getSelectedDropDownOptionName("allLocationsDropDown") + '.</p>');
$("#noClients" + platform).attr("style", "display: block");
$("#theClientsList" + platform).attr("style", "display: none");
} else {
$("#noClients" + platform).attr("style", "display: none");
$("#theClientsList" + platform).attr("style", "display: block");
}
for (i=0; i < client.length; i++) {
var firstName = client[i].getElementsByTagName("givenName")[0].childNodes[0];
var lastName = client[i].getElementsByTagName("familyName")[0].childNodes[0];
var oid = client[i].getElementsByTagName("oid")[0].childNodes[0];
var nhi = client[i].getElementsByTagName("nhi")[0].childNodes[0];
var dwelling = client[i].getElementsByTagName("dwelling")[0].childNodes[0];
var photo = client[i].getElementsByTagName("photo")[0].childNodes[0];
if (!photo) {
photo = "";
} else {
photo = photo.nodeValue;
}
firstName = firstName ? firstName.nodeValue : "";
lastName = lastName ? lastName.nodeValue : "";
oid = oid ? oid.nodeValue : "";
nhi = nhi ? nhi.nodeValue : "";
dwelling = dwelling ? dwelling.nodeValue : "";
var letterDwelling = dwelling ? dwelling[0].toUpperCase() : "";
var letterLastName = lastName ? lastName[0].toUpperCase() : "";
console.log(photo);
dataSource.add({photo: photo, firstName: firstName,lastName: lastName,oid: oid,nhi: nhi,dwelling: dwelling, letterDwelling: letterDwelling, letterLastName: letterLastName});
}
if (clientListViewHasNotLoaded) {
searchFilter = "lastName";
listGroup = "letterLastName"
console.log("e");
$("#theClientsList" + platform).append('<ul id="flat-listview' + platform + '" class="listView' + platform + '" style="width: 100%; margin-bottom:10px; margin-top:10px;"></ul>');
initListView({
field: "lastName",
operator: "startswith",
placeholder: "Search by last name"
}
);
$("#flat-listview" + platform).data("kendoMobileListView").setDataSource(dataSource);
clientListViewHasNotLoaded = false;
}
}
here is the code I'm using to create a web worker, before I take the next step and incorporate my above function:
the script (webServiceScript.js):
self.onmessage = function(event) {
var results = event.data;
// do something
// Done:
postMessage(results);
};
The calling code:
var worker = new Worker('scripts/webServiceScript.js');
worker.onmessage = function(event) {
// Do something with event.data, then hide the spinner.
app.showLoading();
};
app.hideLoading();
worker.postMessage({args: ' foo bar '});
I would like to incorporate my function at the top of the question into the script file (to be used in a web worker). When I incorporate my above function into the script, I need to pass my variable called xml.
Any help greatly appreciated, I'm struggling to understand the documentation here.
As we were discussing in comments, all you need to do is give the browser a chance to do a repaint. You can accomplish that with setTimeout() like this:
app.showLoading()
setTimeout(function() {
getTheClients(xml);
app.hideLoading();
}, 1);
You can't do setTimeout(getTheClients(xml), 1); because that calls getClients() right away and then passes the return result from that to setTimeout(). Instead, you have to pass just a function reference to setTimeout() as shown above.
I have been trying to learn how to write modules in JavaScript. With this attempt I am trying to load 10 pictures from Flickr on page load, and then load 10 more pictures once the user scrolls to the bottom of the page. This is not firing consistantly and I am not sure why.
I would like to load 10 pictures at page load, and then 10 additional pictures each time the user scrolls down to the bottom of the page.
I think the issue is with the curPage property that is called using this.settings.curPage
curPage is incremented in the jaxPhotos method using this.settings.curPage++
I am not sure but I think the issue is with either the jaxPhotos method or the scrollMorePics method.
Here's a fiddle with my module:http://jsfiddle.net/R3Bt7/
Here's my HTML:
<div class="flickrContainer" data-options='{"searchQuery" : "candy", "tagQuery" : "candy", "tagMode": "all", "picsPerPage" : "10", "curPage" : 1}'>
</div>
Here's my JS:
var FlickrModule = (function ($element) {
var flickrFeed = function () {
this.$element = $element;
this.init();
};
flickrFeed.prototype.init = function () {
this.setOptions()
.jaxPhotos(this.settings.curPage)
.onScrollHandler();
};
flickrFeed.prototype.setOptions = function () {
var options = this.$element.data().options;
var defaults = {
searchQuery : '',
tagQuery : '',
tagMode : '',
picsPerPage: '1',
curPage: 1
}
this.settings = $.extend({}, defaults, options);
return this;
};
flickrFeed.prototype.jaxPhotos = function (pageNumber) {
var self = this;
// ajax call to flickr json
$.ajax({
url: '//api.flickr.com/services/rest/?method=flickr.photos.search&api_key=xxxxxxxxxxxxxxxxxxxx&tags=' + this.settings.searchQuery + '&tag_mode=' + this.settings.tagMode + '&page=' + this.settings.currPage + '&per_page=' + this.settings.picsPerPage + '&format=json&jsoncallback=?',
dataType: 'jsonp',
data: JSON,
success: function (data) {
// start assembling some dom elements to wrap around each page
var pageTxtWrap = document.createElement('div'),
pageTxt= document.createElement('p');
pageTxt.textContent = 'Page ' + pageNumber + ' - Scroll down for more pictures!';
pageTxt.innerText = 'Page ' + pageNumber + ' - Scroll down for more pictures!';
pageTxtWrap.className = 'pageTextWrap';
pageTxtWrap.appendChild(pageTxt);
// Use createDocumentFragment() as it is the fastest method of element creation
var docFragPageHdr = document.createDocumentFragment();
docFragPageHdr.appendChild(pageTxtWrap);
document.body.appendChild(docFragPageHdr);
// create variables for easier access to the JSON trees we're using
flickr = data.photos,
flickrLength = flickr.photo.length;
// run through the JSON we just got and assemble the pictures
for (var i = 0; i < flickrLength; i++) {
var farmId = flickr.photo[i].farm,
serverId = flickr.photo[i].server,
photoId = flickr.photo[i].id,
secretId = flickr.photo[i].secret,
imgTitle = flickr.photo[i].title;
var flickImg = document.createElement('img');
flickImg.className = 'flickerImg';
flickImg.id = 'flickImg'+i;
flickImg.title = imgTitle;
flickImg.src = 'http://farm' + farmId + '.staticflickr.com/' + serverId + '/' + photoId + '_' + secretId + '_m.jpg';
var docFragFlickImg = document.createDocumentFragment();
docFragFlickImg.appendChild(flickImg);
document.body.appendChild(docFragFlickImg);
}
}
});
// increase currPage so we can go to the next page of pictures
this.settings.curPage++;
return this;
};
flickrFeed.prototype.onScrollHandler = function () {
$(document).on('scroll', this.scrollMorePics.bind(this));
return this;
};
flickrFeed.prototype.scrollMorePics = function(){
if ( $(window).scrollTop() + $(window).height() > $(document).height() - 50 ) {
console.log('Before ajax curPage = ', this.settings.curPage);
this.jaxPhotos(this.settings.curPage);
console.log('After ajax curPage = ', this.settings.curPage);
};
return this;
};
return flickrFeed;
}( $('.flickrContainer') ));
(function () {
var myModule = new FlickrModule();
})();
A small example on how you can access instance variables and methods based on your code:
var FlickrModule = (function ($) {
var flickrFeed = function ($element) {
this.$element = $element;
this.init();
};
flickrFeed.prototype.init = function(){
console.log('init', this.$element);
};
return flickrFeed;
})(jQuery);
$(function(){
var $container = $('.flickrContainer'),
fm = new FlickrModule($container);
});
http://jsfiddle.net/5nJqM/
I am having a strange issue with using indexeddb API in Javascript. The code below generate the error in the subject line:
var notesdisplay, db;
function initiate(){
notesdisplay = document.getElementById('notesdisplay');
var button = document.getElementById('save');
button.addEventListener('click', addobject);
var request = indexedDB.open('mydatabase');
request.addEventListener('error', showerror);
request.addEventListener('success', start);
request.addEventListener('upgradeneeded', createdb);
}
function showerror(e){
alert('Error: ' + e.code + ' ' + e.message);
}
function start(e){
db = e.target.result;
show();
}
function createdb(e){
var datababase = e.target.result;
var mystore = datababase.createObjectStore('notesTable', {keyPath: 'id'});
mystore.createIndex('searchNotes', 'id', {unique: false});
}
function addobject(){
var title = document.getElementById('notesbox').value;
var mytransaction = db.transaction(['notesTable'], "readwrite");
var mystore = mytransaction.objectStore('notesTable');
var request = mystore.add({id: title});
request.addEventListener('success', show);
document.getElementById('notesbox').value = '';
}
function show(){
notesdisplay.innerHTML = '';
var mytransaction = db.transaction(['notesTable']);
var mystore = mytransaction.objectStore('notesTable');
var myindex = mystore.index('searchNotes');
var newcursor = myindex.openCursor(null, "prev");
newcursor.addEventListener('success', showlist);
}
function showlist(e){
var cursor = e.target.result;
if(cursor){
notesdisplay.innerHTML += '<div>' + cursor.value.id + ' - ' + ' <input type="button" onclick="removeobject(\'' + cursor.value.id + '\')" value="remove"></div>';
cursor.continue();
}
}
function removeobject(keyword){
if(confirm('Are you sure?')){
var mytransaction = db.transaction(['notesTable'], "readwrite");
var mystore = mytransaction.objectStore('notesTable');
var request = mystore.delete(keyword);
request.addEventListener('success', show);
}
}
addEventListener('load', initiate);
When I run this from within Chrome I get the error in the subject line. However, when I run this from Firefox a different error is generated (probably on the same lines).
--
[19:13:54.870] TypeError: db is undefined
Although I am fairly new to Javascript, in my mind the variable db is defined within the start function as here:
function start(e){ db = e.target.result; show(); }
This program is a simplified version of an example I had obtained from a book. This only has one key / value pair.
Any suggestions / pointers as to what could be the issue would be much appreciated.
Many thanks,
vnayak
Your request to open a database connection could be getting blocked. Try adding the following to your initiate function
request.addEventListener('blocked', function() { console.log('blocked'); });
Alright, this one's got me seriously stumped, after trying things out for hours with the block of javascript below I'm still getting the same error in IE's javascript debugger.
The error I'm getting is SCRIPT5007: Unable to get value of the property 'get_id': object is null or undefined.
And below is my code:
AS.SP.ClientActions.ClientProgramEdit_Status = new AS.SP.ClientActions.ButtonStatus();
AS.SP.ClientActions.Can_ClientProgramEdit = function (groupID) {
var OnError = function (sender, args) {
AS.SP.ClientActions.ClientProgramEdit_Status.enabled = false;
RefreshCommandUI();
};
var items = AS.SP.ClientActions.GetSelectedItems();
var count = CountDictionary(items);
if (count === 1) {
var itemID = items[0].id;
if (AS.SP.ClientActions.ClientProgramEdit_Status.itemID != itemID) {
AS.SP.ClientActions.ClientProgramEdit_Status.itemID = itemID;
AS.SP.ClientActions.ClientProgramEdit_Status.enabled = false;
AS.SP.ClientActions.GetUrl(function (rootUrl) {
var fragments = AS.SP.Navigation.ParseUri(rootUrl);
var ctx = new SP.ClientContext(fragments.path);
var web = ctx.get_web();
var props = web.get_allProperties();
ctx.load(web);
ctx.load(props);
ctx.executeQueryAsync(function () {
var listId = 'Client Programs';
var sdlist = web.get_lists().getByTitle(listId);
var locationID = props.get_item('WL_ITEM_ID');
var query = new SP.CamlQuery();
query.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name="len_cp_Location" /><Value Type="Text">' + locationID + '</Value></Eq><Eq><FieldRef Name="len_cp_Client_Status" /><Value Type="Text">Inactive</Value></Eq></And></Where></Query><ViewFields><FieldRef Name="Title" /></ViewFields></View>');
var items = sdlist.getItems(query);
ctx.load(items);
ctx.executeQueryAsync(function () {
var item = items.itemAt(0);
var itemID = item.get_id();
if (itemID == "WL_ITEM_ID") {
AS.SP.ClientActions.ClientProgramEdit_Status.enabled = true;
RefreshCommandUI();
}
}, OnError);
}, OnError);
});
}
}
return AS.SP.ClientActions.ClientProgramEdit_Status.enabled;
}
My theory is that I've done something wrong with my CAML query but at this point I really don't know, any help with this would be greatly appreciated, thanks!
You are using the items variable twice, once on line 9:
var items = AS.SP.ClientActions.GetSelectedItems();
And again inside GetUrl:
var items = sdlist.getItems(query);
There is a name conflict in your execureQueryAsync closure. I would begin by fixing this issue. Which items collection do you want to reference? Do you mean to load the original items variable:
ctx.load(items);
var items = sdlist.getItems(query);