How to Use ParsleyJS with Browserify - browserify

I'm trying to browserify a module containing both jquery and parsleyjs. So far I have this:
var $ = require('jquery');
require('parsleyjs');
If I load this alone, the following line in ParsleyJS throws an ReferenceError jQuery is not defined exception:
window.ParsleyConfig.i18n.en = jQuery.extend(window.ParsleyConfig.i18n.en || {}, {
I think I can use browserify-shim to put jQuery and ParsleyConfig in the global scope, but I could use some help with the details. Also I would prefer a solution that avoids polluting the global scope.
TIA,
- Ole

I will explain my own experience with this problem.
This is not the best way to manage this, I will leave here some clues:
Setup
npm init
npm install --save jquery
npm install --save parsleyjs
app.js
var $ = require('jquery');
window.jQuery = $;
require('parsleyjs/src/i18n/es.js')
require('parsleyjs');
window.Parsley.setLocale('es');
var userFormValidator = require('./validators/userFormValidator.js');
var hello = require('./functions/hello.js');
//global.window.hello = hello;
if (typeof global.window.define == 'function' && global.window.define.amd) {
global.window.define('hello', function () { return hello; });
global.window.define('userFormValidator', function () { return userFormValidator; });
} else {
global.window.hello = hello;
global.window.userFormValidator = userFormValidator;
}
functions/hello.js
module.exports = function () {
alert('hola');
}
validators/userFormValidator.js
module.exports = (function ($) {
var _settings = {};
var _rules = {};
var init = function(settings) {
_settings = {
form : $('#usersForm'),
};
_rules = {
fullname : {
minlength : 3,
maxlength : 80,
required : "true",
},
email: {
minlength : 3,
maxlength : 255,
type : "email",
required : "true",
},
};
_setup();
};
var _setup = function () {
_settings.form.parsley();
var validate = require('./validator.js');
validate(_rules);
};
return {
init: init,
};
})(window.jQuery);
validators/validator.js
var $ = require('jquery');
module.exports = function (rules) {
$.each( rules, function( field, constraints) {
$.each( constraints, function( constraint, value) {
$('[name="' + field +'"]').attr('data-parsley-' + constraint, value);
}.bind(field));
})
}.bind($);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form id="usersForm">
<label for="fullname">Full Name * :</label>
<input type="text" name="fullname" />
<label for="email">Email * :</label>
<input type="text" name="email" />
<input type="submit" />
</form>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript">
userFormValidator.init();
</script>
</body>
</html>

Turn out that the ParsleyJS project has a test browserify.js that shows how to use ParsleyJS with browserify. It does attach all the ParsleyJS objects to the window object, and requires that jQuery do so as well, but at least it works. If anyone has a solution that does this without attaching to the window, please share.
Here are the steps you need to follow to get it working:
mkdir parsleyjs-test
cd parsleyjs-test
npm init (Answer the questions)
npm install --save jquery
npm install --save parsleyjs
npm install --save-dev beefy
touch index.js
CONTENTS OF index.js
window.jQuery = $ = require('jquery');
require('parsleyjs');
TEST WITH BEEFY:
beefy index.js 8080
View results at:
http://localhost:8080
You should see both jQuery and Parsleyjs in the global window namespace. Use ctrl-shift-I to open the web developer tooling in firefox and click on console. Type window in the command line (Bottom of firefox console) and you will see window.jQuery and window.Parsley, etc.
Cheers,
Ole

Related

'x' is not a function when passing parameters in Kotlin Javascript

I keep getting this error: TypeError: Scraper.dumpTitle is not a function
And I can't figure out why...
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Kotlin JS Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script src="out/production/lib/kotlin.js"></script>
<script src="out/production/Scraper.js"></script>
<!--<script>-->
<!--function loaded() {-->
<!--}-->
<!--</script>-->
<script>
$(function() {
Scraper.dumpTitle(document)
})
</script>
</body>
</html>
Main.js
import kotlin.browser.document
/**
* *
* * -
*/
fun main(args: Array<String>) {
println("Hello")
}
fun dumpTitle(doc: dynamic) {
println(doc.title)
}
fun dumpTitle1() {
println(document.title)
}
generated js
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'Scraper'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'Scraper'.");
}
var Scraper = function (_, Kotlin) {
'use strict';
var println = Kotlin.kotlin.io.println_s8jyv4$;
function main(args) {
println('Hello');
}
function dumpTitle(doc) {
println(doc.title);
}
function dumpTitle1() {
println(document.title);
}
_.main_kand9s$ = main;
_.dumpTitle_za3rmp$ = dumpTitle;
_.dumpTitle1 = dumpTitle1;
Kotlin.defineModule('Scraper', _);
main([]);
return _;
}(typeof Scraper === 'undefined' ? {} : Scraper, kotlin);
notes
calling dumpTitle1() works fine.. so the problem I have is only with passing parameters
no need to point out that I can access the document variable in Kotlin without needing to pass it, I know... but I wanted to pass another document object to use
If you're calling a Kotlin function from JavaScript, you need to use the #JsName annotation to give it a stable name. See here for documentation.
#JsName("dumpTitle")
fun dumpTitle(doc: dynamic) {
println(doc.title)
}

WebRTC No function was found that matched the signature provided

I tried this code:
<html>
<head>
</head>
<body>
<video src="" id="video1"></video>
<video src="" id="video2"></video>
<textarea id="lesdp"></textarea><p id="btn">Activer</p>
</body>
<script>
navigator.getUserMedia({audio:true,video:true}, function(stream) {
var video1 = document.querySelector("#video1")
video1.src = window.URL.createObjectURL(stream)
video1.play()
}, function() {
})
var pc = new RTCPeerConnection()
pc.createOffer(function success(offer) {
var sdp = offer;
alert(JSON.stringify(sdp))
}, function error() {
})
var btn = document.querySelector("#btn");
btn.addEventListener('click', function() {
console.log("clicked")
var lesdp = JSON.parse(document.querySelector('#lesdp').value);
pc.setRemoteDescription(new RTCSessionDescription(lesdp), function(streamremote) {
var video2 = document.querySelector("#video2");
video2.srcObject = window.URL.createObjectURL(streamremote)
video2.play()
}, function() {
})
})
</script>
</html>
You can test it here: https://matr.fr/webrtc.html
Open a navigator, copy the popup offer string object, paste it into the textarea, then click "Activer" and look at the error in the console.
So when I click on the "Activer" button, it has this error:
Failed to execute 'createObjectURL' on 'URL': No function was found
that matched the signature provided.
Please help me. I use Google Chrome to test it.
You're calling window.URL.createObjectURL(undefined) which produces that error in Chrome.
streamremote is undefined because setRemoteDescription resolves with nothing by design.
You've only got about half the code needed to do a cut'n'paste WebRTC demo. Compare here.

How to handle external undefined variable in typescript 2.0

I have been developing an application which need to handle an external variable which is defined in my index.html inside <script> tag and window scope. I need to access that in my typescript file to do some operation but during compile its showing error as shown below.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<script>
window.widgetResources = {
'sessionId': '2f60e0a2-3fa2-46f4-9a5c-4a8afe5007c8',
'staticResourceURL': 'http://localhost:9090/OfferFinder/16101/1/0/',
'offers': {
</script>
</head>
<body>
<app>loadings...</app>
</body>
</html>
//WidgetResourcesList.js
export class WidgetResourcesList {
//noinspection TypeScriptUnresolvedVariable
widgetResources = window.widgetResources;
}
//error getting
C:\quickstart>tsc
app/services/WidgetResourcesList.ts(5,28): error TS2339:
`Property 'widgetResources' does not exist on type 'Window'.`
Simple
declare global {
interface Window {
widgetResources: {
sessionId: string,
staticResourceUrl: string,
offers: {}
};
}
}
export class WidgetResourcesList {
widgetResources = window.widgetResources;
}

Browserify talking to another script

I want to use browserify, but I don't want to force users of library to do so. In other words, I want the generated bundle.js to define stuff that other scripts on the same page can find. I tried and failed with:
browserify -o bundle.js src/if.js
where:
::::::::::::::
index.html
::::::::::::::
<script src="bundle.js"></script>
<script>
function go() {
document.getElementById("victim").innerHTML=C();
}
</script>
<body onLoad="go();">
<div id='victim'>Foo</div>
</body>
::::::::::::::
src/if.js
::::::::::::::
var C = require("./c");
::::::::::::::
src/c.js
::::::::::::::
var A = require("./a");
var B = require("./b");
module.exports = function () { return A() + B(); };
::::::::::::::
src/a.js
::::::::::::::
module.exports = function () { return 10; };
::::::::::::::
src/b.js
::::::::::::::
module.exports = function () { return 20; };
This fails with "Reference error: C is not defined."
I don't mind forcing the author of the HTML and his scripts to type something strange, but I don't feel entitled to force him to include browseriy in his build process.
How do I do this?
Bingo! if.js should read
global.C = require("./c");

Unable to print output to the console in dojo

I'm a beginner in dojo, and I'm trying to print the output to console using dojo code. But I don't what's the problem in the following code, and how can I print the output to the console?
<html>
<head>
<script type = "text/javascript" src = "dojo/dojo.js" data-dojo-config = "async: true, isDebug : true" >
</script>
</head>
<body>
<h1 id = "greeting">Hello</h1>
<script>
define(["dojo/dom"],function(dom) {
var Twitter = declare(null, {username:"defaultusername",
say :function(msg)
{
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});
</script>
</body>
</html>
Use require instead of define:
<script>
require(["dojo/dom", "dojo/_base/declare"], function(dom, declare) {
var Twitter = declare(null, {
username: "defaultusername",
say :function(msg) {
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});
</script>
Console works, but your code inside callback function in declare is not being executed until you require it.
You cannot define in inline script code, that is meant to be a class define, put in the topmost line of a class-file, meaning define maps the filename to the returned value of its function.
This means, if you have
dojo_toolkit /
dojo/
dijit/
dojox/
libs/
myWidgets/
foo.js
And foo.js reads
define(["dijit._Widget"], function(adijit) {
return declare("libs.myWidgets.foo", [adijit], function() {
say: function(msg) { console.log(msg); }
});
});
Then a new module is registered, called libs / myWidgets / foo. You should make sure that the returned declare's declaredClass inside each define matches the file hierachy.
That being said, reason why define does not work for you is the explaination above. It is inline and has no src to guess the declaredClass name from. Rewrite your code to define("aTwitterLogger", [":
define("aTwitterLogger", ["dojo/_base/declare", "dojo/dom"],function(declare, dom) {
var Twitter = declare(null, {
username:"defaultusername",
say :function(msg)
{
console.log("Hello "+msg);
}
});
var myInstance = new Twitter();
myInstance.say("Dojo");
});