Looping in PhoneGap-NFC function - javascript

I have a problem in a function PhoneGap-NFC plug-in Intel XDK.
function nova_pulseira(cli_nova_id) {
nfc.addTagDiscoveredListener(function (nfcEvent) {
var tag = nfcEvent.tag;
var = TagID nfc.bytesToHexString(tag.id);
if(TagID! == 0) {
nova_pulseira_input(cli_nova_id, TagID);
} else {
myApp.alert( 'error in reading the bracelet.' 'Notice');
}
});
}
The nfc.addTagDiscoveredListener function is used for reading NFC TAG when occurs nfcEvent.
In the first reading it works normally, but when make the second reading, the nfc.addTagDiscoveredListener function is applied two times, the third reading, it is applied 3 times, and so on.
The only way I found to "stop" this function is using location.reload(); but he returns to the Application home page, and the ideal would be to activate a subpage.
I would, somehow, that nfc.addTagDiscoveredListener function is disabled after applying the nova_pulseira_input(cli_nova_id, TagID); function.
PS: I've used
-> Return false;
-> $ .each (Nfc, function () {this.reset ();});
-> Intel.xdk.cache.clearAllCookies ();
-> $ .ajaxSetup ({Cache: false});
Thanks for the help of all ...

Put the function inside a var and redefine it later:
var tagHandler = function () {
handlerOk();
};
function handlerOk () {
console.log("handlerOk()");
tagHandler = function() {
console.log("disabled..")
};
}
function tag() {
console.log("tag()");
tagHandler();
}
tag();
tag();

Related

Why jQuery validation is not fired when addMethod is called within an object method?

I have this cute class:
validations.js
var Validation = function () {
var load= function () {
$.validator.addMethod("noweirdstuff", function (value, element) {
return !(/\W/.test(value));}, "Username has invalid characters. Only letters, numbres & underscores allowed.");
$.validator.unobtrusive.adapters.add("noweirdstuff", function (options) {
options.rules["noweirdstuff"] = true;
if (options.message) { options.messages["noweirdstuff"] = options.message;}
});
}
return {
init: function () {
load();
}
};
}();
validations.js is bundled and minified with all javascript code into single file. Then, I'm using per page script to load only required code. In this case:
Validation.init();
But it doesn't seem fire the validation. I'm 100% sure that Validation.init() is being called.
It only works when I take it outside:
validations.js
var Validation = function () {
var load = function () {
// goodbye adding validation
}
return {
init: function () {
load();
}
};
}();
$.validator.addMethod("noweirdstuff", function (value, element) {
return !(/\W/.test(value));}, "Username has invalid characters. Only letters, numbres & underscores allowed.");
$.validator.unobtrusive.adapters.add("noweirdstuff", function (options) {
options.rules["noweirdstuff"] = true;
if (options.message) { options.messages["noweirdstuff"] = options.message;}
});
Why?
This is because you are registering your custom script validators after the page is loaded. The validation rules are applied to the whole document once unobtrusive validator loads, if your rules and validators haven't been added to the stack by then, they will be ignored.
I believe you could call $.validator.unobtrusive.parse(document) after you have added your rules and validators, I'm not 100% sure this would work or if would apply validators twice.
Edit: Rephrased the answer
Edit: Added possible solution

Using callbacks JS / JQuery

I am trying to use callbacks in order to effectively "overwrite" the standard alert and confirm actions in JavaScript.
The code I am using is a bit long winded so I jotted it into a working jsfiddle
I am trying to get it so that a callback is used to determine true or false, but it is coming back as undefined as the callback function is fired before a click is
My questions, is how can I change this to effectively overcome the functions value being returned before the click is called via jQuery?
Example usage:
<button onclick="confirm('This is a test')">Show dialog (confirm)</button>
Example jQuery events:
if (confirm("This is a test")) {
alert("Confirmed")
}
else {
alert("Did not confirm")
}
Edit
Using a loop within the callback messed it us a lot...
You are mixing things up when waiting for the return value.
You are passing dialog.checkForInput as the callback. But in the dialog.show() function you do:
var ret = callback();
...
return ret;
But the dialog.checkForInput function doesn't return anything, it merely sets event listeners.
As events all run "asynchronously" it would be more sensible to give your dialog a callback function which will be run when there actually would be an event. Meaning: in your checkForInput function (I would name it differently, but whatever) run the callback and pass the action as a parameter. Something like:
checkForInput: function () {
$(document).ready(function () {
$(".dialog_confirm_okay").on("click", function () {
dialog.hide();
callback('confirm');
})
$(".dialog_confirm_cancel").on("click", function () {
dialog.hide();
callback('cancel');
})
$(".dialog_alert_okay").on("click", function () {
dialog.hide();
callback('alert');
})
})
}
And your callback could look like this (assuming your callback was called dialogCallback):
function dialogCallback ( action ) {
alert('Dialog closed with action: ' + action);
};
Some points I conclude from your code:
The reason why statement callback() return undefined value is because dialog.checkForInput return nothing.
The $(document).ready inside checkForInput is async, so returned value from that block is meaningless (it won't become the return value of the checkForInput as well).
And also you put the return statement inside event declaration, it'll become return value of the event (when the event triggered), not the checkForInput.
I did some modification on your code, this one working. Basically I create new method called onclick, which will be called every time button yes or no is clicked.
show: function (e_type, e_content) {
var d = dialog;
var d_head = e_type == "confirm" ? "Confirm Action" : "Error";
var d_buttons = e_type = "confirm" ? d.parts.buttons.okay + d.parts.buttons.cancel : d.dparts.buttons.alert_okay;
var _dialog = d.parts.main + d.parts.head.replace("{DIV_HEADER}", d_head) + d.parts.body + e_content + "<div class='dialog_button_container'>" + d_buttons + "</div>" + d.parts.footer;
$("body").append(_dialog);
},
onclick: function (ret) {
$(".errors").text("Return value was: " + ret);
},
showError: function (e_content) {
dialog.show("alert", e_content);
dialog.checkForInput();
},
showConfirm: function (e_content) {
dialog.show("confirm", e_content);
dialog.checkForInput();
},
checkForInput: function () {
var self = this;
$(".dialog_confirm_okay").on("click", function () {
dialog.hide();
self.onclick(true);
})
$(".dialog_confirm_no").on("click", function () {
dialog.hide();
self.onclick(false);
})
$(".dialog_alert_okay").on("click", function () {
dialog.hide();
self.onclick(false);
})
},
Working example: https://jsfiddle.net/p83uLeop/1/
Hope this will help you.
EDITED
From the comment section I assume that you want this alert to become a blocking function like window.confirm, so you can do something like if (confirm('Are you sure')).
But sadly it's impossible to achieve this case.
I have some suggestion, you can encapsulate your code better, and implement clean callbacks or promises. Maybe something like this:
showConfirm(function (ok) {
if (ok) {
// "yes" clicked
} else {
// "no" clicked
}
})
// or
showConfirm(function () {
// "yes" clicked
}, function () {
// "no clicked"
})
// or
var customConfirm = showConfirm()
customConfirm.on('yes', function () {
// "yes" clicked
})
customConfirm.on('no', function () {
// "no" clicked
})

First jquery plugin

Im trying to make my first jquery plugin.. but actually i dont know what im doing wrong here.
$(document.ready(function()
{
var plugin = (function()
{
//this function is not accessible from the outside
function privateFunction()
{
}
//these functions are
return
{
alert1: function()
{
alert('Hallo');
},
alert2: function()
{
alert("hi");
}
}
})()
//but it is not working :/
plugin.alert1();
});
it is not executing one of the alerts. Am i putting some semicolons wrong?
i checked if all were closed
Javascript's automatic semicolon insertion will add a semicolon after return and undefined is returned.
Your code will look like
return;
{...
Replace
return
{
Should be
return {
You're also missing the ) after document in the first line of code.
Demo
$(document).ready(function() {
var plugin = (function() {
//this function is not accessible from the outside
function privateFunction() {
// Code Here
}
//these functions are
return {
alert1: function() {
alert('Hallo');
},
alert2: function() {
alert("hi");
}
};
}());
//but it is not working :/
plugin.alert1();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Trigger addEventListener on live element that is not in the DOM (native JavaScript)

I'm stuck with my modal popup plugin since a week.
I'll try to explain as much as i can but first, here is the jsfiddle: http://jsfiddle.net/hideo/yth37hhf/27/
I know the code contains some other functions but they are useful for my plugin.
So, my issue is that the function "triggerLinkAction" contains an addEventListener which is not fired.
(function() {
Window.prototype.triggerLinkAction = function(){
var triggeredLink = document.getElementById("triggeredOtherAction");
var inputTarget = document.getElementById("inputText");
console.log('triggeredLink',triggeredLink);
triggeredLink.addEventListener("click", function (e) {
alert('If this pops out, I will be very happy!!!');
e.preventDefault();
inputTarget.value = "This text should be on the input field...";
}, true);
}
})();
The targeted element is inside the modal, and this modal is displayed by clicking on the link "A small modal".
When the plugin calls ShowModal(), I trigger the TransitionEnd event to call a function
[.... code ...]
function ShowModal() {
vars.popupContainer.classList.add("show");
hsdk.PrefixedEvent(vars.popupOverlay, "TransitionEnd", function (e) {
executeFunctions();
});
}
[.... code ...]
The executeFunctions() will check which functions need to be called:
[.... code ...]
function executeFunctions() {
if (vars.opts && vars.opts.fn) {
var allFunctions = vars.opts.fn.split(',');
for (var i = 0; i < allFunctions.length; i++)
{
var functionName = allFunctions[i];
var functionToExecute = window[functionName];
if(typeof functionToExecute === 'function') {
functionToExecute();
}
}
}
}
[.... code ...]
There are some comments on the javascript part about the plugin, but feel free to ask if I can provide any other information.
PS: I don't care about IE for now ;-)

Passing parameters to a event listener function in javascript

Hello I have some code in which I take user input through in html and assign it to,two global variables
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
Which next show up in this addeventlistener function as parameters of the whowon function
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
The click event is meant to trigger the whowon function and pass in the parameters
function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {
if (FirstScore > SecondScore) {
FirstTeam.win();
SecondTeam.lose();
} else if (FirstScore < SecondScore) {
SecondTeam.win();
} else {
FirstTeam.draw();
SecondTeam.draw();
}
}
However the values are null,as I get a cannot read properties of null error on this line
var spursscoref = document.getElementById("spursscore").value;
I am pretty sure the problem is coming from the addlistener function,any help would be appreciated
Well you could do something like this -
$( document ).ready(function() {
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
});
Wrap your code in $(document).ready(function(){}). This will ensure that all of your DOM elements are loaded prior to executing your Javascript code.
Try putting all of your code inside this
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
My guess is that your code is executed before the html actually finished loading, causing it to return null.

Categories

Resources