I've tried to create a default Phonegap barcode scanner trough plugin basic installation, but it didn't work well. I don't know what's happening. Here is my code:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
console.log('-');
console.log(cordova);
console.log('-');
console.log(cordova.plugins.barcodeScanner);
console.log('-');
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
};
It's basically the default Phonegap plugin panel. The problem is that it doesn't recognize the cordova.plugin.barcodeScanner. I've created the project trough the Phonegap Windows tool and ran the cordova plugin add cordova-plugin-statusbar command inside the folder. Please help me, I can't see any code example of this working. Thanks.
you can call getScanner() function onClick event in javascript Read More Here
function getScanner(){
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
); }
let me know if its not working..
Related
In the edit modal for my company entity, I open the address entity create modal. This allows the user to create an address for the company. On the .done of the address create app service method, I trigger an event using the abp.event.trigger method. The company edit modal then watches for this event so that it can create an entry into the companyAddress entity. Soon as the companyAddress entity app service method ends, on .done event, I turn off the event trigger. However, after the first instance of creating an address, when the user adds more addresses the trigger mechanism is firing multiple times and causing duplicate entries in the companyAddress table. I have debugged this over and over and read the docs for abp event triggers and cannot figure out how this happening. Any help would be much appreciated.
Create address modal js
this.save = function () {
if (!_$form.valid()) {
return;
}
var address = _$form.serializeFormToObject();
_modalManager.setBusy(true);
_addressService.createAddress(
address
).done(function (result) {
abp.notify.info(app.localize('SavedSuccessfully'));
abp.event.trigger('addressCreated', {
id: result
});
console.log('addressCreated event triggered for id: ' + result);
_modalManager.close();
}).always(function () {
_modalManager.setBusy(false);
});
};
Edit company modal js
abp.event.on('addressCreated', function (item) {
console.log('addressCreated event caught for id: ' + item.id);
//Call company address service
var _companyAddressService = abp.services.app.companyAddress;
_companyAddressService.createCompanyAddress({
CompanyId: $("#CompanyId").val(),
AddressId: item.id
}).done(function () {
abp.event.off('addressCreated', {
id: null
});
console.log('addressCreated event turned off for id: ' + item.id);
abp.notify.success(app.localize('AddressCreated'));
abp.ui.clearBusy('.modal-body');
});
});
Here is google chrome console showing the duplication.
I just tested the modals again, I entered about 8 different addresses via the create modal for 2 differnt companies. For this test, the duplication issue did not happen. But the issue where the event does not fire for each address created keeps happening. As you can see from the console log below, the ID number 2,3,5 and 6 did not generate the "started" log entry. My companyAddress table is also missing the entry for these 4 IDs, so the event did not trigger.
Edit company modal.js full updated code
var EditCompanyModal = (function ($) {
app.modals.EditCompanyModal = function () {
var _modalManager;
var _companyService = abp.services.app.company;
var _$Form = null;
this.init = function (modalManager) {
_modalManager = modalManager;
_$Form = _modalManager.getModal().find('form[name=EditCompany]');
$(".modal-dialog").addClass("modal-lg");
_$Form.validate();
};
this.save = function () {
if (!_$Form.valid()) {
return;
}
var company = _$Form.serializeFormToObject();
_modalManager.setBusy(true);
_companyService.updateCompany(
company
).done(function () {
abp.notify.info(app.localize('SavedSuccessfully'));
_modalManager.close();
abp.event.trigger('app.editCompanyModalSaved');
}).always(function () {
_modalManager.setBusy(false);
});
abp.event.off('addressCreated', addressCreated); // Turn off this handler
};
var _editModal = new app.ModalManager({
viewUrl: abp.appPath + 'Nursing/Address/EditModal',
scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Address/_EditModal.js',
modalClass: 'EditAddressModal'
});
var _createModal = new app.ModalManager({
viewUrl: abp.appPath + 'Nursing/Address/CreateModal',
scriptUrl: abp.appPath + 'view-resources/Areas/Nursing/Views/Address/_CreateModal.js',
modalClass: 'CreateAddressModal'
});
$('#add_new_address').click(function (e) {
_createModal.open();
});
$('#addressTiles').on('click', '.btnEditAddress', function () {
var addressID = $(this).parent().find("input").first().val();
_editModal.open({ id: addressID });
});
abp.event.on('addressCreated', addressCreated);
//After address create event, save company address Id
function addressCreated(item) {
console.log(new Date().toUTCString() + ' - addressCreated started for id: ' + item.id);
//Call company address service
var _companyAddressService = abp.services.app.companyAddress;
_companyAddressService.createCompanyAddress({
CompanyId: $("#CompanyId").val(),
AddressId: item.id
}).done(function () {
console.log('addressCreated event turned off for id: ' + item.id);
abp.notify.success(app.localize('AddressCreated'));
abp.ui.clearBusy('.modal-body');
});
}
};})(jQuery);
Chrome console logs for updated JS code
From the documentation on Register To Events:
You can use abp.event.off method to unregister from an event. Notice that; same function should be provided in order to unregister. So, for the example above, you should set the callback function to a variable, then use both in on and off methods.
You're passing in a dummy object:
abp.event.off('addressCreated', {
id: null
});
Do this:
function addressCreated(item) {
console.log('addressCreated event caught for id: ' + item.id);
//Call company address service
var _companyAddressService = abp.services.app.companyAddress;
_companyAddressService.createCompanyAddress({
CompanyId: $("#CompanyId").val(),
AddressId: item.id
}).done(function () {
abp.event.off('addressCreated', addressCreated); // Turn off this handler
console.log('addressCreated event turned off for id: ' + item.id);
abp.notify.success(app.localize('AddressCreated'));
abp.ui.clearBusy('.modal-body');
});
}
abp.event.on('addressCreated', addressCreated);
The addressCreated function is executing not at all sometime[s]
You're only calling .on once per EditCompanyModal, and then .off-ing it.
Move the .off into this.save = ....
Update
Move the .off into this.init = ....
this.init = function (modalManager) {
_modalManager = modalManager;
// ...
_modalManager.onClose(function () {
abp.event.off('addressCreated', addressCreated); // Turn off this handler
});
};
I have applied same custom event to the event object in the backbone with 2 different callbacks.
var ourObject = {};
_.extend(ourObject, Backbone.Events);
function dancing (msg) { console.log("We are dancing. " + msg); }
function jumping (msg) { console.log("We are jumping. " + msg); }
ourObject.on("move", dancing);
ourObject.on("move", jumping);
When I trigger move event using ourObject.trigger("move", "Yeah!");,it will trigger both the callbacks.
How should I prevent triggering second callback from first callback?
You can pass an object containing a flag which acts as an event object as second argument:
function dancing(msg, event) {
console.log(event); // flag: false
event.flag = true;
console.log("We are dancing. " + msg);
}
function jumping(msg, event) {
console.log(event); // flag: true
if(!event.flag) return;
console.log("We are jumping. " + msg);
}
ourObject.trigger("move", 'test', {
flag: false
});
Or you can simply do something like:
function dancing (msg) {
this.dancingTriggered = true;
console.log("We are dancing. " + msg);
}
function jumping (msg) {
if(this.dancingTriggered){
this.dancingTriggered = false;
return;
}
console.log("We are jumping. " + msg);
}
Or just use simple variable available in the scope of these callbacks
I am new to cordova and plugins..
I have created a webappp, in my app i need to download files from server..
so i have used cordova background download plugin.. and i m using intel xdk.. so i have impoted plugin there..
cordova plugin github
now.. when i download file, on notification bar its showing downloading file.. BUT ITS SHOWING PLUGIN PACKAGE NAME WHILE DOWNLOADING.... but file save as its original name.... here it is my code..
var app = {
fileName: "tera hone.mp3",
uriString: "https://api.soundcloud.com/tracks/133667943/stream?client_id=67739332564a7130c3a05f90f2d02d2e", // 38.3 MB
// Application Constructor
initialize: function() {
this.bindEvents();
},
downloadFile: function(uriString, targetFile) {
var lblProgress = document.getElementById('lblProgress');
var complete = function() {
lblProgress.innerHTML = 'Done';
};
var error = function (err) {
console.log('Error: ' + err);
lblProgress.innerHTML = 'Error: ' + err;
};
var progress = function(progress) {
lblProgress.innerHTML = (100 * progress.bytesReceived / progress.totalBytesToReceive) + '%';
};
try{
var downloader = new BackgroundTransfer.BackgroundDownloader();
// Create a new download operation.
var download = downloader.createDownload(uriString, targetFile);
// Start the download and persist the promise to be able to cancel the download.
app.downloadPromise = download.startAsync().then(complete, error, progress);
} catch(err) {
console.log('Error: ' + err);
}
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
document.getElementById('btnStart').addEventListener('click', this.startDownload);
document.getElementById('btnStop').addEventListener('click', this.stopDownload);
document.getElementById('btnFileInfo').addEventListener('click', this.getFileInfo);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.startDownload();
},
startDownload: function () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(app.fileName, { create: true }, function (newFile) {
app.downloadFile(app.uriString, newFile);
});
});
},
stopDownload: function () {
app.downloadPromise && app.downloadPromise.cancel();
},
getFileInfo: function () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(app.fileName, { create: true }, function (fileEntry) {
fileEntry.file(function (meta) {
document.getElementById('lblFileInfo').innerHTML =
"Modified: " + meta.lastModifiedDate + "<br/>" +
"size: " + meta.size;
});
}, function(error) {
document.getElementById('lblFileInfo').innerHTML = "error: " + error;
});
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
this is my javascript file invoke from my html file.. from cordova plugin..
also when i stop downloading.. it stops but app suddenly crashed everytime....
sorry for my bad english..
I am trying to use jquery with phantomjs. I tried a standalone example and it worked fine. Here is what I did:
var page = require('webpage').create();
page.open("http://www.phantomjs.org", function(status) {
page.onConsoleMessage = function(msg) {
console.log("message recvd: " + msg);
};
var result;
page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() {
console.log("loading jquery");
});
setTimeout(function() {
page.evaluate(function() {
console.log("$(\"title\").text() -> " + $("title").text());
});
}, 1000);
}
Here is the output I got:
loading jquery
message recvd: $("title").text() -> PhantomJS | PhantomJS
In the above code snippet, I have used setTimeout() on evaluate function because includeJs() would execute asynchronously and need some time to load jquery. If I do not use setTimeout() or use a small value for timeout, it doesn't work.
However, when I try the same code in my application it doesn't work. Here is what I have:
var baseSetup = function(guid, page, config, request, response) {
/* enable the console output inside the callback functions */
page.onConsoleMessage = function (msg) {
console.log(guid + ": console msg: " + msg);
};
/* used for ignoring potential alert messages when evaluating js code */
page.onAlert = function (msg) {
console.log(guid + " (alert): alert msg: " + msg);
};
/* suppress the error messages */
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' +
t.file +
': ' +
t.line +
(t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(guid + ": " + msgStack.join('\n'));
};
}
module.exports = function extractionDriver(responseFromUrl, responseToUser, page, request) {
console.log(page.customHeaders['guid'] + ": extractionDriver, status = " + responseFromUrl.status);
if(page.isLocalFile || responseFromUrl.status !== 0)
{
var viewportStr = page.customHeaders['viewportStr'];
console.log(page.customHeaders['guid'] + ": Setting viewport size: " + viewportStr);
var viewportObj = parseViewport(viewportStr);
page.viewport = viewportObj;
page.evaluate(function(w,h) {
document.body.style.width = w + "px";
document.body.style.height = h + "px";
}, viewportObj.width, viewportObj.height);
page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() {
console.log("loading jquery");
});
setTimeout(function() {
page.evaluate(function() {
console.log("$(\"title\").text() -> " + $("title").text());
});
}, 1000);
}
And this is what I see when I run my application:
d8db6045-a0e8-11e4-a619-6949593d958d: ERROR: ReferenceError: Can't find variable: $
TRACE:
-> phantomjs://webpage.evaluate(): 3
-> phantomjs://webpage.evaluate(): 4
-> phantomjs://webpage.evaluate(): 4
The log line "loading jquery" is never printed and jquery is never loaded.
I have tried wrapping up the evaluate() function inside the callback of includeJs() but that didn't work either (no console log printed).
What could be going wrong here? Please let me know if I should provide more information.
That is why page.includeJs has a callback, so you can put the code that depends on jQuery in there. The callback is called when the referenced JavaScript is already loaded. Welcome to another level on the road to the callback hell.
I experienced one time though that this didn't work for some reason. The workaround was to set a global variable in the includeJs callback and use waitFor to wait for the global variable to be set outside of the includeJs callback.
var _loadIndicator = false;
page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() {
_loadIndicator = true;
});
waitFor(function check() {
return _loadIndicator;
}, function onReady() {
page.evaluate(function() {
console.log("$(\"title\").text() -> " + $("title").text());
});
}, 10000);
I just have troubles with this, but my mistake was that, i tried phantom.injectJs, not page.injectJs (jerk). And then, if status is success, put
page.injectJs('lib/jquery.min.js');
and try
page.evaluate(function(){
console.log($("body").length);
});
I'm trying to test a Push Notification app with Phonegap. I registered my project at GCM and added my Project Number at the SenderID var. Here's the code:
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
var pushNotification = window.plugins.pushNotification;
alert("Register called");
pushNotification.register(this.successHandler, this.errorHandler,{"senderID":"543180841340","ecb":"app.onNotificationGCM"});
},
successHandler: function(result) {
alert('Callback Success! Result = '+result)
},
errorHandler:function(error) {
alert(error);
},
onNotificationGCM: function(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
console.log("Regid " + e.regid);
alert('registration id = '+e.regid);
document.getElementById('regId').value = e.regid;
}
break;
case 'message':
alert('message = '+e.message+' msgcnt = '+e.msgcnt);
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
},
onNotificationAPN: function(event) {
var pushNotification = window.plugins.pushNotification;
alert("Running in JS - onNotificationAPN - Received a notification! " + event.alert);
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.badge) {
pushNotification.setApplicationIconBadgeNumber(this.successHandler, this.errorHandler, event.badge);
}
if (event.sound) {
var snd = new Media(event.sound);
snd.play();
}
}
};
I get the first alert ("Register called") but not the regID. I'm using the Phonegap Developer app for Android and the "phonegap serve" command to get it live. I tried to download the app too, but still doesn't work.
Firing the ("Register called") Doesn't mean that the push notification registration is instantiated but it means that receivedEvent is called and that is good.
1- Make sure that push notification plugin is included in config.xml and the pushNotification object is not null.
to include the plugin to config.xml: add <gap:plugin name="com.phonegap.plugins.pushplugin" />
2- Make sure that the sender id is OK "no typos".