javascript file cordova.. how to pass value through variable - javascript

I am developing intel cordova app...
to download files from server , i have included cordova file download plugin but it has data that i want to pass through variable...
here is my code:
var app = {
fileName: "PointerEventsCordovaPlugin.wmv", //<-- pass this value through variable (dynamic)
uriString: "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv", // <-- this one also
// Application Constructor
initialize: function() {
this.bindEvents();
},
....
I have added fileName and uristring.. but i want to add that value dynamically from variable.. how can i do this?????
cordova plugin link
please if you know anything about this than reply...

Following the example from the link you provided, remove the fileName and uriString fields from the app object, and parameterize the needed functions. For example, startDownload will become:
startDownload: function (fileName, uriString) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(fileName, { create: true }, function (newFile) {
app.downloadFile(uriString, newFile);
});
});
},

Related

Cannot find name 'jQuery' error in controller.js

I am developing a UI5 app in VS Code.
I added a new count function to the *.controller.js file, and in order to display the count from the server, I am using jQuery like in the following code:
jQuery.each(this._mFilters, function (sFilterKey, oFilter) {
oModel.read("/portfolios/$count", {
filters: oFilter,
success: function (oData) {
var sPath = "/" + sFilterKey;
oViewModel.setProperty(sPath, oData);
}
});
});
Unfortunately, I get the following error:
Does anyone know why was the error triggered and how it can be fixed?
Any help or suggestion is much appreciated.
I assume this._mFilters is an object. In that case, try with:
Object.keys(this._mFilters).map(sFilterKey => {
const oFilter = this._mFilters[sFilterKey];
oModel.read("/portfolios/$count", {
filters: [ oFilter ],
success: function(sCount) {
const sPath = `/${sFilterKey}`;
oViewModel.setProperty(sPath, +sCount);
},
});
});
Also the parameter filters awaits an array instead of a single Filter instance.
If jQuery is still preferred, include "sap/ui/thirdparty/jquery" (formerly "jquery.sap.global") to the dependency list of the controller.
sap.ui.define([
"sap/ui/core/mvc/Controller",
// ...,
"sap/ui/thirdparty/jquery",
], function(Controller,/*...,*/ jQuery) {
// jQuery is here available
});

autoComplete.js - how to resolve autoComplete is not defined

I want to use autocomplete.js in my application.
I have installed the package using yarn add #tarekraafat/autocomplete.js. I am using webpack 4.28 to bundle the javascript files and have require("#tarekraafat/autocomplete.js/dist/js/autoComplete"); to import the package into the application and placed the bundled file at the bottom before the closing BODY tag.
In my custom.js file, I am creating a new instance of autoComplete as follows:
new autoComplete({
data: {
src: async () => {
document.querySelector("#autoComplete_results_list").style.display = "none";
document.querySelector("#autoComplete").setAttribute("placeholder", "Loading...");
const source = await fetch("/employee/search");
const data = await source.json();
return data;
},
key: "name"
},
selector: "#autoComplete",
placeHolder: "type employee name to search...",
threshold: 0,
searchEngine: "strict",
highlight: true,
dataAttribute: { tag: "value", value: "" },
maxResults: Infinity,
renderResults: {
destination: document.querySelector("#autoComplete"),
position: "afterend"
},
onSelection: feedback => {
document.querySelector(".selection").innerHTML = feedback.selection.food;
document
.querySelector("#autoComplete")
.setAttribute("placeholder", `${event.target.closest(".autoComplete_result").id}`);
console.log(feedback);
}
});
However, on running the application, I am getting an error Uncaught ReferenceError: autoComplete is not defined with a reference to the location where I am creating the new instance.
I have read the getting started documentation and looked at the demo code and I can't figure out what I am missing. How do I resolve the error?
Your problem is in your import, you are not import the autoComplete correctly, so when you using the new autoComplete you are having error.
Change the require("#tarekraafat/autocomplete.js/dist/js/autoComplete"); to import autoComplete from '#tarekraafat/autocomplete.js';, put this on top of your file, right after jquery or something
Write your code inside
$(document).ready(function(){
// Write your Code Here
});

Meteor FS.Collection image doesn't render on upload

Whenever I upload an image with FS.Collection using FileSystem, the image doesn't renders and I get a 503 error. But if I refresh the page the image will render and I get no error. So I had to to set that images path to a public folder using ostrio:meteor-root, so whenever I upload an image, the page refreshes. I'm fetching the image URL from a Mongo.Collection, not from my FS.Collection.
When I upload an image I store the url on Adverts:
"_id" : "knCMZPK8RrY5Y7GQo",
"reference" : 102020026,
"pics" : {
"pic" : [
{
"url" : "http://localhost:3000/cfs/files/Images/6fHhBT3ky5iAJnQfw"
}
]
},
Images.js:
var imageStore = new FS.Store.FileSystem("Images", {
path: Meteor.absolutePath + '/public/uploads'
})
Images = new FS.Collection("Images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
},
}
});
if (Meteor.isServer) {
Images.allow({
insert: function(userId, party) {
return true;
},
update: function(userId, party) {
return true;
},
download: function(userId, party) {
return true;
},
remove: function(userId, party) {
return true;
}
});
}
Image not rendering:
ANSWER:
Instead of using FS collection I switched to ostrio:files.
Since I wanted to just upload the images to the document that I was updating (I have a reactive-table with my collection data, each row is clickable and contains a document, when I click a row I use iron:router to navigate to a page with AutoForm that updates that single document) I make a Meteor.call in the client to send the document _id to the server.
Meteor.call('docId', this._id)
It seemed like the image wasn't rendering because it was creating the thumbnail before finishing the upload.
So to fix this I made a afterUpload call back server-side on docId Method:
FSCollection.off('afterUpload')
FSCollection.on('afterUpload', function(fileRef){
Update Mongo.Collection (...)
}
If I don't use .off before .on it keeps incrementing the time that the code inside the callbak is executed. When the first image is uploaded the code executes correctly, when the second one is uploaded the code is executed twice and so on.

Plupload: perform custom check before starting upload

I have an MVC 5 view with a form and a plupload file uploader section. Upload is triggered by a button on the form. I have no problem uploading file chunks to the server and setting the parameters to the query string and all, but what I do have a problem with is starting the upload only after a custom sanity check has been performed.
Here's what I have tried:
var uploader = new plupload.Uploader({
runtimes: 'html5',
drop_element: 'upload',
browse_button: 'browse',
url: "../UploadFile",
chunk_size: "1024kb",
multipart_params: { "uid": "uid", "chunk": "chunk", "chunks": "chunks", "name": "name" },
init: {
PostInit: function(file) {
document.getElementById("filelist").innerHTML = "";
document.getElementById('submit-all').onclick = function () {
document.getElementById("infoPopup").style.visibility = "visible";
document.getElementById('submit-all').enabled = false;
var uuid = Math.uuidFast();
document.getElementById("uid").value = uuid;
uploader.settings.multipart_params = { uid: uuid, chunk: file.chunk, chunks: file.chunks, name: file.name };
if (checkReq) {
uploader.start();
}
return false;
};
},
The crucial part here is this:
if(checkReq){
uploader.start();
}
"checkReq" is my custom sanity check script that verifies that form values are not nonsensical (e.g. single form entries might be perfectly valid while in combination they are simply wrong, etc.).
So the above does not prevent the upload, the check script is not even fired, Firebug console output shows no error.
Since googling tells me that there is also a "BeforeUpload" event, I tried this:
BeforeUpload: function(up, file) {
if (checkReq) {
up.stop();
return false;
}
return true;
},
Which also does not seem to fire at all.
Edit: Next attempt, I put the call to my checkReq fuction into BeforeUpload in "preinit", which should fire before any chunking etc is done, so before the upload is prepared. This also failed although I have no idea why it does not fire:
var uploader = new plupload.Uploader({
runtimes: 'html5',
drop_element: 'upload',
browse_button: 'browse',
url: "../UploadFile",
chunk_size: "1024kb",
multipart_params: { "uid": "uid", "chunk": "chunk", "chunks": "chunks", "name": "name" },
preinit: {
BeforeUpload: function (up) {
if (checkReq) {
uploader.stop();
uploader.splice(0, uploader.files.length);
return false;
}
return true;
}
},
init: {
PostInit: function(file) {
...
I had used "dropzone.js" before, and my script worked fine with that but I found that I needed chunked uploads so I had to move to plupload and now my script is being ignored.
Could someone please tell me where I am being stupid here? Thanks!
Got it solved.
It's a nasty, ugly hack, but it works:
Made the "actual" submit/upload button hidden
Made a second button that acts as pre-submit button with onclick function
onclick function calls checkReq and if that returns true, the function calls the click() function of the "actual" submit/upload button
Like I said: nasty but it works.

Why is YUI.add required when specifying YUI modules and if it is required how can non-YUI modules work?

We use the YUI3 loader to manage loading our javascript and css files. As part of the bootstrap js code on each page, we have something like the following:
YUI({
...
groups: {
...
myGroup: {
modules: {
"my-module": {
...
path: "MyModule.js",
requires: [ "yui-base" ]
},
}
...
}
}
}).use("my-module", function (Y) {
Y.MyModule.doStuff();
});
MyModule.js has something like the following:
YUI.add('my-module', function (Y) {
Y.MyModule = function () {
...
_validator: Y.Lang.isString
};
}, '3.4.0', {
requires: [ "yui-base" ]
});
YUI also claims here that the loader can be used with non-YUI3 "modules" given that they have their dependencies specified in the configuration. They give the following example module configuration for a yui2 group:
yui2: {
combine: true,
base: 'http://yui.yahooapis.com/2.8.0r4/build/',
comboBase: 'http://yui.yahooapis.com/combo?',
root: '2.8.0r4/build/',
modules: { // one or more external modules that can be loaded along side of YUI
yui2_yde: {
path: "yahoo-dom-event/yahoo-dom-event.js"
},
yui2_anim: {
path: "animation/animation.js",
requires: ['yui2_yde']
}
}
}
This suggests that YUI is smart enough to load and run YUI2's animation.js only after yahoo-dom-event.js has loaded and run.
What I don't understand is, if this works for non-YUI modules, how come I have to wrap my own modules with YUI.add and the redundant requires list (since requires is also specified in the configuration)?
I tried dropping the add wrapper (I replaced it with (function (Y) { /* module content */ })(YUI);), but this lead to a js error on page load: Y.Lang is undefined. Thus, it seems that somehow without the wrapping add() call the script is getting executed before the base yui script where Y.Lang is defined. However, if that is the case, then won't this be a problem for non-YUI modules (which don't call YUI.add())?
It's important to distinguish between custom modules that utilize YUI3 features (sandboxed Y.Lang, etc) and completely external code.
In the first case, the YUI.add() wrapper is always necessary, because the sandbox Y variable isn't available outside the module callback (the second argument to YUI.add()). The repetition of module configuration is unfortunately necessary in hand-written modules due to constraints within Y.Loader (where the combo-loading magic happens). Modules that employ YUI's build tools have the wrapper and metadata added automagically.
With completely external code, you only need to provide the fullpath config property, and YUI will do the right thing. Internally, YUI knows when a given <script> request finishes, and associates that success with the configured module name.
To simplify things, I'll be using YUI.applyConfig to demonstrate the config bits. Using that, you can create any number of YUI sandboxes (via YUI().use(...)) with the config mixed in, instead of repeating it all over the place.
YUI.applyConfig({
"modules": {
"leaflet": {
"fullpath": "http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"
},
"my-leaflet-thing": {
"path": "path/to/my-leaflet-thing.js",
"requires": [
"base-build",
"node-base",
"leaflet"
]
}
}
});
my-leaflet-thing.js looks something like this:
YUI.add("my-leaflet-thing", function (Y) {
// a safe reference to the global "L" provided by leaflet.js
var L = Y.config.global.L;
Y.MyLeafletThing = Y.Base.create("myLeaflet", Y.Base, {
initializer: function () {
var id = this.get('node').get('id');
var map = L.map(id);
// etc
}
}, {
ATTRS: {
node: {
getter: Y.one
}
}
});
// third argument is a version number,
// but it doesn't affect anything right now
}, "1.0.0", {
"requires": [
"base-build",
"node-base",
"leaflet"
]
});
Given this setup, since this requires a non-asynchronous library, you can safely do this:
YUI().use("my-leaflet-thing", function (Y) {
var instance = new Y.MyLeafletThing({
"node": "#foo"
});
});
Note: If an external file does dynamic loading of its own (e.g., async Google Maps API), YUI will only be aware of the initial request success, not the entire chain of files loaded. To address this, you'll need to use the querystring callback argument in the fullpath config, associated with some globally-exposed callback in the module that requires it.
In these cases, it's better to do an internal Y.use() (note the sandbox variable) to better encapsulate the required globals.
Config:
YUI.applyConfig({
"modules": {
"google-maps-api": {
"fullpath": "http://maps.googleapis.com/maps/api/js" +
"?v=3&sensor=false&callback=initGMapsAPI"
},
"my-google-map-thing": {
"path": "path/to/my-google-map-thing.js",
"requires": [
"base-build",
"node-base"
]
}
}
});
my-google-map-thing.js:
YUI.add("my-google-map-thing", function (Y) {
// publish a custom event that will be fired from the global callback
Y.publish('gmaps:ready', {
emitFacade: true,
fireOnce: true
});
// private sentinel to determine if Y.use() has been called
var isUsed = false;
// expose global function that matches "callback" parameter value
Y.config.global.initGMapsAPI = function () {
// Y.config.global.google is now available
Y.fire('gmaps:ready');
};
Y.MyGoogleMapThing = Y.Base.create("myGoogleMap", Y.Base, {
initializer: function () {
Y.on('gmaps:ready', this.render, this);
if (!isUsed) {
isUsed = true;
Y.use("google-maps-api");
}
},
render: function () {
// safe reference to global "google"
var google = Y.config.global.google;
var id = this.get('node').get('id');
var map = new google.maps.Map(id, {
// ...
});
// etc
}
}, {
ATTRS: {
node: {
getter: Y.one
}
}
});
}, "1.0.0", {
"requires": [
"base-build",
"node-base"
]
});
To sum up: YUI.add() is only necessary when writing modules that depend on YUI3 sandboxed resources. Loading external code, as long as it is all synchronous, is as simple as employing the fullpath config property. Asynchronous external loading is a bit hairier, but still possible.

Categories