The script is being ran on the android OS at the moment.
Globals File
///Store Global Variables
var Globals = {
Storage: window.localStorage,
OfflineMode: false,
GetSettingsString : function()
{
return JSON.stringify(Settings);
},
SetSettings : function(str)
{
try
{
Settings = JSON.parse(str);
if(Settings.Id != 0)
VelocityMeetings.app.navigate("scan/", { root: true });
}
catch(e)
{
alert(e);
Globals.SetSettings();
}
},
///Experimentation Function
SetSettings: function () {
//Settings = JSON.parse(str);
Settings.OfflineMode = false,
Settings.Username = "mager1794",
Settings.Password = "mn1apwfm",
Settings.Id = 0;
alert("Values Set Manually");
//VelocityMeetings.app.navigate("scan/", { root: true });
},
Init: function () {
// this.SetSettings(/*FileStream.ReadFile("settings.dat")*/);
alert("test2");
this.SetSettings(FileStream.ReadFile("settings.dat"));
alert("test3");
},
Save: function () {
FileStream.WriteFile("settings.dat", GetSettingsString());
}
};
document.addEventListener("deviceready", ondeviceReady(), false);
// Cordova is ready to be used!
//
function ondeviceReady() {
alert("test");
Globals.Init();
}
FileSystem File
var FileStream = {
WriteFile: function (filename, objtoWrite) {
_filename = filename;
_dataobj = objtoWrite;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSWrite, fail);
},
WriteFile: function (filename, objtoWrite, type) {
_filename = filename;
_dataobj = objtoWrite;
_type = type;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSWrite, fail);
},
ReadFile: function (filename) {
alert("ReadFile Called");
_filename = filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, _gotFSRead, fail);
return _dataread;
},
_dataread: null,
_dataobj: null,
_type : "WRITE",
_filename: "",
_gotFileWriter: function (writer) {
writer.onwrite = function (evt) {
_isBusy = false;
};
if(_type=="WRITE")
writer.write(_dataobj);
if (_type == "APPEND")
{
writer.seek(writer.length);
writer.write(_dataobj);
}
writer.abort();
},
_gotFSWrite: function (fileSystem) {
fileSystem.root.getFile(_filename, { create: true }, _gotFileEntryWrite, fail);
},
_gotFileEntryWrite: function (fileEntry) {
fileEntry.createWriter(_gotFileWriter, fail);
},
_gotFSRead: function (fileSystem) {
alert("gotFSRead Called");
fileSystem.root.getFile(_filename, { create: true }, _gotFileEntryRead, fail);
},
_gotFileEntryRead: function (fileEntry) {
alert("gotFileEntryRead Called");
fileEntry.file(_gotFileRead, fail);
},
_gotFileRead: function (file) {
alert("gotFileRead Called");
var reader = new FileReader();
reader.onloadend = function (evt) {
_dataread = evt.target.result;
};
reader.readAsText(file);
},
_fail: function (error) {
throw "File Failed";
}
};
the GotFSRead function is never being reached and I cannot figure out why, I've placed in the alerts just so I can watch as it progressed through the functions. Additionally, can you store a callback in a variable? because it seems that the read file function is going to need a callback in order to successfully receive the data.
Yes, in Javascript functions are objects, so they can be assigned to variables just like you're doing in your code here.
The function references in your FileStream object are missing this references, such as this._gotFSRead. For example:
ReadFile: function (filename) {
alert("ReadFile Called");
this._filename = filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, this._gotFSRead, this._fail);
return this._dataread;
},
There are many places where this is missing, and you need to fix your _fail references too.
Related
I try to create a function where the user uploads the file and then showing the image that's been uploaded to a div. But I need to have the name of the file in order to add the src attr to
Seems like UIKIT 3 does not have a way where I can get the name of the file when it's dropped or selected.
Anyone can help this, please?
Here's the code from UIKIT, and here's the docs they provide
UIkit.upload('.js-upload', {
url: '../config/forms.php',
beforeSend: function () {
console.log('beforeSend', arguments);
},
beforeAll: function () {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function () {
console.log('error', arguments);
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (arguments) {
console.log('completeAll', arguments);
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
}
});
JS side:
UIkit.upload('.js-upload', {
url: 'file_upload.php',
multiple: false,
mime: "image/*",
completeAll: function () {
uploaded_filename = arguments[0].response;
}
});
PHP Side:
$uploads_dir = PUBLIC_FOLDER."uploads";
$tmp_name = $_FILES['form-drop-place']['tmp_name'];
$image_name = $_FILES['form-drop-place']['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$new_name = "newname." . $ext;
$new_place = $uploads_dir . "/" . $new_name;
if ( move_uploaded_file($tmp_name, $new_place) ) {
die($new_name);
} else {
die();
}
I have the following code in my visual studio and it works perfectly well au a UWP app on my desktop win10, albeit it does not work on my windows phone as a UWP app. I also tried running my simple webapp as from a webserver and loading it in the Edge and it works perfectly.
What should be the problem?
My code looks like this. I omitted some parts:
var model = {
db: {},
goalsobj: {},
goals: [],
init: function() {
var openReq = window.indexedDB.open("GoalsDB");
openReq.onupgradeneeded = function (event) {
model.db = event.target.result;
var objectStore = model.db.createObjectStore("Goals", { keyPath: "id" });
objectStore.createIndex("id","id", {unique:true});
};
openReq.onsuccess = function (event) {
model.db = event.target.result
model.db.transaction("Goals", "readonly").objectStore("Goals").count().onsuccess = function (event) {
if (event.target.result == 0) {
console.log("indexeddb empty");
var goalstemplate = {
id: "idee",
goals: [{ "name": "Task1" }, { "name": "Task2" }, { "name": "Task3" }]
}
var addReq = model.db.transaction("Goals", "readwrite").objectStore("Goals").add(goalstemplate);
} else {
model.db.transaction("Goals", "readonly").objectStore("Goals").get("idee").onsuccess = function (e) {
model.goalsobj = e.target.result;
//console.log(e.target.result);
model.goals = model.goalsobj.goals;
goalfunc.makeList(); //model should not talk to view, but this case it is amust, because if I remove this, it does not render at boot.
}
}
}
openReq.onerror = function (event) {
console.log("Operation failed");
}
}
},
add: function(goalname) {
model.goals.push(
{
"name": goalname
});
model.savedb();
},
move: function (id,updown) {
if (updown == "up") {
model.goals.splice((id-1), 0, model.goals.splice(id, 1)[0]);
};
if (updown == "down") {
model.goals.splice((id+1), 0, model.goals.splice(id, 1)[0]);
};
},
savedb: function(){
//console.log(goals);
var update = model.db.transaction("Goals", "readwrite").objectStore("Goals").put(model.goalsobj);
update.onerror = function (event) {
console.log(event);
};
},
};
Now When I rund this cond on my device it sais:
Unhandled exception at line 28, column 25 in ms-appx-web://1318f74a-397e-4958-aa6b-c8d11b7c5dce/js/main.js
0x800a138f - JavaScript runtime error: Unable to get property 'goals' of undefined or null reference
I have tested your code in my device (Device: Microsoft RM-1118 OSVersion:WindowsMobile 14393). It is working fine. As you can see I placed a button on the html page. The action of button click will execute model.init(), and then I set a break-point at model.goals = model.goalsobj.goals;. When click button the second time and model.goals will be set right value.
So I think the issue may happen in your target device or your GoalsDB was destroyed. Because the cause of Unable to get property 'goals' of undefined or null reference is that model.goalsobj was not set right value. Please check whether those operations have changed your database structure, such as moving operation. You can show more detail about your target device, and I will help you.
(function () {
document.getElementById("createDatabase").addEventListener("click", createDB, false);
function createDB() {
model.init();
}
})();
var model = {
db: {},
goalsobj: {},
goals: [],
init: function () {
var openReq = window.indexedDB.open("GoalsDB");
openReq.onupgradeneeded = function (event) {
model.db = event.target.result;
var objectStore = model.db.createObjectStore("Goals", { keyPath: "id" });
objectStore.createIndex("id", "id", { unique: true });
};
openReq.onsuccess = function (event) {
model.db = event.target.result
model.db.transaction("Goals", "readonly").objectStore("Goals").count().onsuccess = function (event) {
if (event.target.result == 0) {
console.log("indexeddb empty");
var goalstemplate = {
id: "idee",
goals: [{ "name": "Task1" }, { "name": "Task2" }, { "name": "Task3" }]
}
model.db.transaction("Goals", "readwrite").objectStore("Goals").add(goalstemplate);
} else {
model.db.transaction("Goals", "readonly").objectStore("Goals").get("idee").onsuccess = function (e) {
model.goalsobj = e.target.result;
//console.log(e.target.result);
if (model.goalsobj.goals != undefined) {
model.goals = model.goalsobj.goals;
} else {
console.log(e.target.result);
}
//goalfunc.makeList(); //model should not talk to view, but this case it is amust, because if I remove this, it does not render at
}
}
}
openReq.onerror = function (event) {
console.log("Operation failed");
}
}
},
add: function (goalname) {
model.goals.push(
{
"name": goalname
});
model.savedb();
},
move: function (id, updown) {
if (updown == "up") {
model.goals.splice((id - 1), 0, model.goals.splice(id, 1)[0]);
};
if (updown == "down") {
model.goals.splice((id + 1), 0, model.goals.splice(id, 1)[0]);
};
},
savedb: function () {
//console.log(goals);
var update = model.db.transaction("Goals", "readwrite").objectStore("Goals").put(model.goalsobj);
update.onerror = function (event) {
console.log(event);
};
}
};
Ive been trying to get this code working for firefox, that I got from
nsITraceableChannel, Intercept HTTP Traffic and from How to get an url from nsITraceableChannel?, Ive been googling for the answer, with no luck.
What I would like to do is intercept certain links, and change them.
Any help is welcomed
The error I get is function statement requires a name witch points to observe: function(aSubject, aTopic, aData) part of the code
const Cc = Components.classes;
const Ci = Components.interfaces;
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.addObserver(httpRequestObserver,
"http-on-examine-response", false);
observerService.removeObserver(httpRequestObserver,
"http-on-examine-response");
//--------------------------------------------------------
var httpRequestObserver =
{
observe: function(aSubject, aTopic, aData)
{
if (aTopic == "http-on-examine-response")
{
}
},
QueryInterface : function (aIID)
{
if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports))
{
return this;
}
throw Components.results.NS_NOINTERFACE;
}
}
//------------------------------------------------------------
function TracingListener() {
this.originalListener = null;
}
TracingListener.prototype =
{
onDataAvailable: function(request, context, inputStream, offset, count) {
this.originalListener.onDataAvailable(request, context, inputStream, offset, count);
},
onStartRequest: function(request, context) {
this.originalListener.onStartRequest(request, context);
},
onStopRequest: function(request, context, statusCode) {
this.originalListener.onStopRequest(request, context, statusCode);
},
QueryInterface: function (aIID) {
if (aIID.equals(Ci.nsIStreamListener) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_NOINTERFACE;
}
}
observe: function(aSubject, aTopic, aData)
{
if (aTopic == "http-on-examine-response") {
var newListener = new TracingListener();
aSubject.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = aSubject.setNewListener(newListener);
}
}
aSubject = aSubject.QueryInterface(Ci.nsIChannel);
var uri = aSubject.URI;
// original URI that was requested before any other resolver steps
// and/or redirects.
var ouri = aSubject.originalURI;
ch = Services.io.newChannel("https://google.com/", null, null);
console.log(ch.toString());
// "[xpconnect wrapped nsIChannel]"
ch.QueryInterface(Ci.nsITraceableChannel);
console.log(ch.toString());
// "[xpconnect wrapped (nsISupports, nsIChannel, nsITraceableChannel)]"
console.log(ch instanceof Ci.nsIUploadChannel);
// true
console.log(ch.toString());
// "[xpconnect wrapped (nsISupports, nsIChannel, nsITraceableChannel, nsIUploadChannel)]"
// the variable "ch" is known to implement the four given interfaces at this point.
Copy paste this it works:
// const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
// Cu.import('resource://gre/modules/Services.jsm');
Services.obs.addObserver(httpRequestObserver, "http-on-examine-response", false);
// Services.obs.removeObserver(httpRequestObserver, "http-on-examine-response");
//--------------------------------------------------------
var httpRequestObserver = {
observe: function(aSubject, aTopic, aData) {
// if (aTopic == "http-on-examine-response") {} // no need for this, we added observer for `http-on-examine-response` so we know for sure this only triggers for `http-on-examine-response`
var newListener = new TracingListener();
aSubject.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = aSubject.setNewListener(newListener);
}
/* // what was the point of this block of code?
,
QueryInterface: function(aIID) {
if (aIID.equals(Ci.nsIObserver) || aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
}
*/
}
//------------------------------------------------------------
function TracingListener() {}
TracingListener.prototype = {
onDataAvailable: function(request, context, inputStream, offset, count) {
console.log('data available');
this.originalListener.onDataAvailable(request, context, inputStream, offset, count);
},
onStartRequest: function(request, context) {
this.originalListener.onStartRequest(request, context);
},
onStopRequest: function(request, context, statusCode) {
this.originalListener.onStopRequest(request, context, statusCode);
},
QueryInterface: function(aIID) {
if (aIID.equals(Ci.nsIStreamListener) || aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
}
}
// what the hell? this is not part of an object? why observe colon?
/*
observe: function(aSubject, aTopic, aData) {
if (aTopic == "http-on-examine-response") {
var newListener = new TracingListener();
aSubject.QueryInterface(Ci.nsITraceableChannel);
newListener.originalListener = aSubject.setNewListener(newListener);
}
}
*/
// whats with all this junk? is it supposed to be in an observer??
/*
aSubject = aSubject.QueryInterface(Ci.nsIChannel);
var uri = aSubject.URI;
// original URI that was requested before any other resolver steps
// and/or redirects.
var ouri = aSubject.originalURI;
ch = Services.io.newChannel("https://google.com/", null, null);
console.log(ch.toString());
// "[xpconnect wrapped nsIChannel]"
ch.QueryInterface(Ci.nsITraceableChannel);
console.log(ch.toString());
// "[xpconnect wrapped (nsISupports, nsIChannel, nsITraceableChannel)]"
console.log(ch instanceof Ci.nsIUploadChannel);
// true
console.log(ch.toString());
// "[xpconnect wrapped (nsISupports, nsIChannel, nsITraceableChannel, nsIUploadChannel)]"
// the variable "ch" is known to implement the four given interfaces at this point.
*/
Update
Someone asked me how to get the response source with this, so I created a gist out of it: https://gist.github.com/Noitidart/d0b08629ee2804538ad9#file-_ff-addon-snippet-copyofrequestsource-js-L16
In controller, i am returning object from factory. The method is callback type.
But the problem is that the object is not returing.
My implementation is as:
.factory('fileReadFactory', ['$http',
function ($http) {
var objRead = {
setReadObject: '',
setPath: 'comMyTaxi',
setFileName: '',
status: false,
errorCode: ''
};
var factory = {};
factory.fileRead = function RequestFileSystem(fileName) {
alert('factory start');
objRead.setFileName = fileName;
try {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, createDirectory, fail);
objRead.status = true;
return objRead;
} catch (e) {
return objRead;
}
}
///write steps starts
function createDirectory(fs) {
fs.root.getDirectory(objRead.setPath, {create: true, exclusive: false}, onSuccessCreateFile, fail);
}
function onSuccessCreateFile(dirEntry) {
dirEntry.getFile(objRead.setFileName + '.txt.gz', null, gotFileEntryRead, fail);
}
function gotFileEntryRead(fileEntry) {
// alert('in 2 type step2');
fileEntry.file(gotFileReading, fail);
}
function gotFileReading(file) {
// alert('in 2 type step3');
readFile(file);
}
function readFile(file) {
// alert('in 2 type step4');
var reader = new FileReader();
reader.onloadend = function (e) {
// alert("Text is: "+this.result);
objRead.setReadObject = this.result;
}
reader.readAsText(file);
// alert('reading Ends');
}
//write file ends
function fail(err) {
alert('error ' + err.code);
objRead.errorCode = err.code;
throw e;
}
return factory;
}]);
And my call inside controller is like
var objReturn = fileReadFactory.fileRead('myProfile');
alert(objReturn.status);
alert(JSON.parse(objReturn.setReadObject));
if(objReturn.status){
var obj= JSON.parse(objReturn.setReadObject);
// alert(obj);
// alert('Inside Object World');
$scope.myprofile = obj;
}
I am not getting the if block. So how do i manage the call back;
Try to call your service and execute the alerts in then() function. You should also read about promises: http://andyshora.com/promises-angularjs-explained-as-cartoon.html
var objReturn = fileReadFactory.fileRead('myProfile').then(function(){
alert(objReturn.status);
alert(JSON.parse(objReturn.setReadObject));
if(objReturn.status){
var obj= JSON.parse(objReturn.setReadObject);
// alert(obj);
// alert('Inside Object World');
$scope.myprofile = obj;
}
});
In terms of efficiency,
what's the fastest and most standard way to tweak a function in javascript?
Plugin-style coding would be like this.
; (function ($, window, document, undefined) {
var pluginName = "SoketManager",
dataPlugin = "plugin_" + pluginName,
settings = {
target: this,
width: 350,
height: 150,
theme: 'default'
}
var Plugin = {
// instance...
}
Plugin.prototype = {
connect: function() {
//something.
},
disconnect: function() {
//something.
},
sendmessage: function() {
//something...
},
etc: function() {
}
//etc2: function() .......
}
$.fn[pluginName] = function (arg, contents) {
var args, instance;
if (typeof arg === 'string' && typeof instance[arg] === 'function') {
args = Array.prototype.slice.call(arguments, 1);
return instance[arg].apply(instance, args);
}
And using global variable would be like this..
var SocketManager = {
sock: '',
connect: function () {
var stdInfo = new JSONClientParameters();
var socket = io.connect('http://192.168.1.39:3000', {
query: stdInfo.toGetString()
//'reconnect': true,
// 'reconnection delay': 500,//default 500
//'max reconnection attempts': 10
});
kdbSocketManager.ksock = socket;
socket.on('connect', function () {
alert('successfully connected to the database!!');
});
},
disconnect: function () {
this.ksock.disconnect();
},
sendMessage: function (pMsg, pTargetId) {
this.ksock.emit('sendMessage', { msg: pMsg, targetId: pTargetId });
},
I see no point in coding like the plugin-way. Is it much more simple and easy to read to code like the latter one? could somebody explain this in detail?