Uncaught ReferenceError: $ is not defined how to solve? - javascript

I have a problem in a click button redirect to another page in cordova build, the error is an Uncaught ReferenceError: $ is not defined
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener('resume', onResume.bind(this), false);
$("getas").click(function () {
alert("The paragraph was clicked.");
});
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!--
Customize the content security policy in the meta tag below as needed. Add 'unsafe-inline' to default-src to enable inline JavaScript.
For details, see http://go.microsoft.com/fwlink/?LinkID=617521
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<title>CatechesisMobileApp</title>
<!-- MobileApp references -->
<link href="css/index.css" rel="stylesheet" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/index.js"></script>
</head>
<body>
<p>Mobile App - Inicio</p>
<button id="getas">Ver Alunos (GET ALL)</button>
<br />
<br />
<button id="geta">Ver Aluno (GET ID)</button>
<br />
<br />
<button id="posta">Inserir Aluno (POST)</button>
<!-- Cordova reference, this is added to your app when it's built. -->
</body>
</html>
what am i doing wrong? I already try in onclick button "document.location.href='example.html'" and simply dont work
Thanks

Philip Clegg was very close in his comment. You need to pass jQuery into the closure. Here's an SO question explaining it
(function ($) {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener('resume', onResume.bind(this), false);
$("#getas").click(function () {
alert("The paragraph was clicked.");
});
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )(jQuery);

getas is an id so you should select it with
$("#getas")

Related

cordova android backbutton behavior [duplicate]

I am overriding my device back button per the documentation that I attach event listener to backbutton with argument of false after the deviceready event.
I have done so like this:
// Smart App object
define([
'routes',
'cordova',
'angular',
'angularRoute',
'angularResource',
'angularTouch',
'config',
'controllers',
'services',
'directives',
'helpers'
], function(appRoute) {
var oApp = {
_app: {},
init: function() {
console.log('init');
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
console.log('ok device ready');
document.addEventListener('backbutton', function() {
console.error('deviceback start');
angular.element('.ng-scope').scope().back();
console.error('deviceback end');
}, false);
// ...
}
// ...
I have worked crazily to figure out why hitting the device button is not triggering this backbutton event i attached, i dont even see the console.error messages in the console. I am testing on Android right now I haven't tested on any of the other Phone OS'es yet.
The console.log('ok device ready') does fire and my app works properly, the device backbutton is overridden in that its default functionality is not taking place, however as stated, my function is not taking place either.
I read other stackoverflow topcis and they said the Cordova version landed a fix, but my Cordova version is much after theirs, my .cordova/config.json file tells me:
{
"lib": {
"www": {
"id": "com.tigoenergy.smart",
"version": "3.5.0"
}
}
}
It is 3.5 and then my info.txt tells me it is 5.0.0:
Node version: v0.10.25
Cordova version: 5.0.0
Config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!-- config.xml reference: https://build.phonegap.com/docs/config-xml -->
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
Does anyone have any ideas?
Try using the normal way of using cordova events.
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
//Add your back button implementation.
}
official documentation here
Modified code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Tigo SMART Installation</title>
<script type="text/javascript" src="apps/installation/js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="apps/installation/js/index.js"></script>
<script type="text/javascript" src="apps/installation/js/fastclick.min.js"></script>
<script type="text/javascript" src="apps/installation/js/sha512.js"></script>
<script type="text/javascript" src="bower_components/uri.js/src/URI.min.js"></script>
<script type="text/javascript" src="js/extlogin.js"></script>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" type="text/css" href="apps/installation/css/index.css" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
//mycode
console.log('ok loaded');
document.addEventListener("deviceready", onDeviceReady, false);
});
// Wait for device API libraries to load
//
/*function onLoad() {
console.warn('ok loaded')
document.addEventListener("deviceready", onDeviceReady, false);
}
*/
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
console.log('ok device ready');
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
console.log('ok backey downed');
}
</script>
</head>
<body>
<div ng-view></div>
<script data-main="bin/SmartApp" src="bower_components/requirejs/require.min.js"></script>
<img style="opacity:0;visibility:hidden;" class="loader" src="img/loader.gif" />
</body>
</html>
Few reference links here and here
The issue was I was importing cordova.js in an iframe even though it was already in the parent window scope. I didn't know it would break it and thought I had to import cordova.js in the iframe. Removing the from the iframe fixed it.
Try This
$(document).ready(function () {
document.addEventListener("backbutton", onBackKeyDown, false);
});
function onBackKeyDown() {
alert('ok backey downed');
}
Make sure these files are link in your page
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>

How to write unit tests for events in backbone.js

I begin my adventure with write unit tests so please be indulgence. In my app I am using jQuery, backbone.js and underscore.js and for tests mocha.js and chai.js. I have problem because I have no idea how to test events using this tools. Fox example I have function which changes value of input. It call after change checkbox value.
test.html file:
<!DOCTYPE html>
<html>
<head>
<title>Backbone.js Tests</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="js/lib/mocha.css" />
<script src="js/lib/mocha.js"></script>
<script src="js/lib/chai.js"></script>
<!-- <script src="js/lib/sinon.js"></script> -->
<script>
// Setup
var expect = chai.expect;
mocha.setup('bdd');
// Run tests on window load event.
window.onload = function () {
(window.mochaPhantomJS || mocha).run();
};
</script>
<!-- App code -->
<script src="../public/static/js/libs/jquery-2.1.4.min.js"></script>
<script src="../public/static/js/libs/js.cookie-2.1.0.min.js"></script>
<script src="../public/static/js/libs/bootstrap.min.js"></script>
<script src="../public/static/js/libs/underscore-min.js"></script>
<script src="../public/static/js/libs/backbone-min.js"></script>
<script src="../public/static/js/libs/backbone-relational.min.js"></script>
<script src="../public/static/js/libs/backbone-super.min.js"></script>
<script src="../public/static/js/libs/handlebars-v4.0.5.min.js"></script>
<script src="../public/static/js/application.js"></script>
<script src="../public/static/js/main.js"></script>
<script src="../public/static/js/views/register.js"></script>
<script src="../public/static/js/views/modals/sign-in-modal.js"></script>
<script src="../public/static/js/views/modals/sign-up-modal.js"></script>
<script src="../public/static/js/helpers/forms.js"></script>
<script src="../public/static/js/helpers/alerts.js"></script>
<script src="../public/static/js/helpers/inpage-alerts.js"></script>
<script src="../public/static/js/collections.js"></script>
<script src="../public/static/js/models.js"></script>
<script src="../public/static/js/kodilla.lib.js"></script>
<script src="../public/static/js/views/knowledge-base.js"></script>
<script src="../public/static/js/libs/tether.min.js"></script>
<!-- Tests -->
<script src="js/spec/register.spec.js"></script>
</head>
<body>
<div id="mocha"></div>
</body>
</html>
register.js file:
App.Views.Register = Backbone.View.extend({
events: {
'click input[name="terms"]' : 'changeTermsConfirmation',
'click [type=submit]': 'onSubmitForm'
},
initialize: function(options) {
this.$termsConfirmedAtHidden = this.$('input[name="terms_confirmed_at"]');
},
changeTermsConfirmation: function(e) {
if ($(e.currentTarget).is(":checked")) {
this.$termsConfirmedAtHidden.val(Math.floor(Date.now() / 1000));
} else {
this.$termsConfirmedAtHidden.val('');
}
},
onSubmitForm: function() {
if (!this.$el.find('input[name="terms"]').is(':checked')) {
analytics.track('auth_register_not_checked_terms');
}
}
});
register.spec.js file:
$(document).ready(function() {
describe('Register Form', function() {
App.registerView = new App.Views.Register();
describe('initialize() function', function() {
it('Should initialize this.$termsConfirmedAtHidden variable by HTML object', function () {
expect(App.registerView.$termsConfirmedAtHidden).to.be.a('object');
});
});
describe('changeTermsConfirmation() function', function() {
it('Should set value of $termsConfirmedAtHidden element', function () {
//how to test this function
});
});
});
});
My question is how to write sensible unit test for "changeTermsConfirmation()" function. I'll be thankful for others notes, usage tips.
Maybe I can help you out with a few bits of info which might get you started.
Mocha/Chai is modular, so first you need to include a mocking/spying library into your project. The default choice for most people seems to be Sinon (along with Sinon-Chai).
Then you can examine and unit test your event handler:
Create a view instance for your test.
Set up a spy on the view method you want to test (changeTermsConfirmation in your case)
Trigger the event by calling trigger on your view instance
Your expectation can check how often your method has been called, and with which arguments, and what its return value has been.
If you don't care about any of that and just want to test view state changes, you don't need a spy (and you don't need to include a library like Sinon). Just create a view instance, call trigger and examine the result.

Cordova Alert Button

I'm trying to put an alert on a button in Cordova, I don't understand why it's not working.
I started a new cordova blank project with console.
See below my code :
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<button id = "textlocal">Test Local</button>`
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js :
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');
document.getElementById("textlocal").addEventListener("click", textLocal);
},
// 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);
},
function textLocal(){
alert('test');
}
};
app.initialize();
Maybe my textLocal() function is not at the right place, but I can't figurate how to fix it.
Thank you a lot for your patience and your help.
There was a JavaScript error in your code. Please try this code now. Maybe you need to add the "textLocal" listener up to the "deviceready" listener.
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');
document.getElementById("textlocal").addEventListener("click", this.textLocal);
},
// 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);
},
textLocal: function() {
alert('Test');
}
};
app.initialize();
Your code have a syntax error.
And this function never will call if you not associate with button.
You need put a onclick listener. You can use onclick tag like this:
<button id="textlocal" onclick="textLocal()">Test Local</button> (without space)
or using jquery
$("#textlocal").on("click", textLocal);
Remove this from head tag and try
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
If still its not working, your deviceready function executing before DOM load. So you should put it inside $(document).ready if you are using jquery or just in onload event. By the way add addEventListener is not good approach for such simple operation, just use onclick listener.
I allow myself to bring an interesting way to understand why it's not working. I'm not so familiar with cordova development but I create a cordova project on Visual Studio and get this :
index.html
<button id="textlocal" data-role="button">Alert</button>
index.js (in ondevice ready) :
$('#textlocal').click(textLocal);
test.js :
function textLocal() {
alert('test');}
And this solution works. However, I wouldn't like to work on visual studio but directly with command prompt and outside any editor.
It's a little the same thing as my demand above, but still can't find a way to make it happend. Hope that could help you to answer my problem.
Thank you.

Cordova inappbrowser: executeScript on loadstart

Is it possible to executeScript() on loadstart event in Cordova inAppBrowser? Here is my standalone example I made to try to make it happen:
<!DOCTYPE html>
<html>
<head>
<title>Standalone Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var iabRef = null;
function testFunction() {
iabRef.executeScript({
code: {'alert("It is alive! ALIVE!")'}
});
}
function onDeviceReady() {
iabRef = window.open('http://telegraph.co.uk', '_self', 'location=no', 'zoom=no', 'hardwareback=yes');
iabRef.addEventListener('loadstart', testFunction);
}
</script>
</head>
<body>
</body>
</html>
Doesn't work for me though. Config.xml allow origin is set to *. Any suggestions?
Thanks!
Yes, it possible to executeScript() on loadstart.Remove {} from alert part as follows:
function testFunction() {
iabRef.executeScript({
code: 'alert("It is alive! ALIVE!");'
});
}
Hope this works
After a little bit of wandering I found that changing "_self" to "_blank" makes it work. So:
iabRef = window.open('http://telegraph.co.uk', '_blank', 'location=no', 'zoom=no', 'hardwareback=yes');

Window.postMessage() issue

I cannot get any data if I use different domains. If I run it on the same server, no problem with it - message is obtained.
index.html:
<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function popupResize() {
var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
// var popup = window.open('https://foo/index.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
window.addEventListener(
'message',
function(event) {
console.log(event.data);
},
false
);
}
</script>
</head>
<body>
Go!
</body>
popup.html:
<head>
<title>Game history details</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function postSize() {
var h = 100;
var w = 200;
opener.postMessage([h, w], '*');
}
</script>
</head>
<body onload="postSize();">
test 1
</body>
How to get it working using different servers?
Problem 1
popup.addEventListener(
You need to listen for the event on your original window, not on the popup. The popup is where the message comes from, not where it is sent.
Use window.addEventListener( or just addEventListener(.
Problem 2
{h, w}
ES6 shorthand property names are not supported by IE, Opera, Safari or Android Mobile. They are best avoided.
Problem 3
parent.postMessage({h, w}, '*');
You are sending a message to the opening window, not the parent frame. There is no parent frame (so parent recurses onto window).
That should be:
opener.postMessage({h: h, w: w}, '*');
Problem 4
<script type="text/javascript">
var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
Your script does not have permission to open a new window except in response to a user event. That code needs moving into a function and then called from, for instance, a click event.
If I run it on the same server, no problem with it - message is obtained.
It is the combination of problems 1 and 3 that cause this. You are binding an event handler to the popup (which you can only do from the opening window if it is on the same origin) and you are posting a message from the popup to itself (because parent === window).
Complete, albeit not best practise, code that works in my tests:
http://localhost:7007/index.html
<!DOCTYPE html>
<html>
<script>
addEventListener("message", function (event) {
document.body.appendChild(document.createTextNode(event.data));
});
function pop() {
window.open("http://127.0.0.1:7007/popup.html");
}
</script>
<input type="button" onclick="pop()">
http://127.0.0.1:7007/popup.html
<!DOCTYPE html>
<html>
<script>
opener.postMessage([123, 456], '*');
</script>
<h1>popup</h1>
The eventListener should be attached to window instead of popup:
window.addEventListener(
'message',
function (event) {
console.log(event.data);
},
false
);
In your child window (popup), you are posting a message to the parent window, but the eventListener is attached to the child window instead.

Categories

Resources