requirejs 2.1.11 + jquery mobile 1.4.2 throw error - jquery-mobile

It seems that requireJS does not work properly with jquery mobile 1.4.2
in the app.js I have the minimum configuration for RequireJS 2.1.11
requirejs.config({
'baseUrl': 'js',
'paths': {
'jquery': 'lib/jquery-1.10.2',
'jquerymobile': 'lib/jquery_mobile/jquery.mobile-1.4.2'
}
});
And then when I am trying to use jquerymobile dependancy I have:
define(['require', 'jquery', 'jquerymobile' ], function (require, $) {
console.log(success)
})
This shows an error in the Chrome console
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:63342/app/www/js/demos/js/jquery.js
Uncaught Error: Script error for: demos/js/jquery
http://requirejs.org/docs/errors.html#scripterror require.js:141
This is caused by jquery mobile code:
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "demos/js/jquery" ], function ( $ ) {
factory( $, root, doc );
return $.mobile;
});
} else {
// Browser globals
factory( root.jQuery, root, doc );
}
}
When I change with jquery mobile 1.3.2 it seems that require JS is working correctly. Is there a way to use requireJS with Jquery mobile 1.4.2 ?

You're not using the correct source. When I go straight to the official source, I see:
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], function ( $ ) {
factory( $, root, doc );
return $.mobile;
});
} else {
This is exactly what I would expect: jQuery Mobile depends on jquery, which is the way you always should require jQuery with RequireJS.
The demos/js/jquery dependency that you see in the code you show in your question does not make much sense. It would be possible to make it work but it would require everybody who uses jQuery Mobile to go through an unnecessary configuration hoop. This is a big red flag that something is wrong.

Related

Dart Project with RequireJS

I am trying to include web3.js into my Dart project. I am trying to do this via requirejs
I've created a requirejs config, which appears to load a valid web3 instance except, now my dart code never initializes! It appears that the requirejs main.js prevents my main.dart from executing. Could really use advice on how to get everything playing nicely.
main.js
requirejs.config({
appDir: ".",
baseUrl: "scripts",
paths: {'web3': 'https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min'}
});
require(['web3'], function(web3) {
console.log("Loaded :)");
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
console.log(web3);
return web3;
});
The function does get called and is passed an initialized web3 object.. except strong text

Fetch API not working with Rails + React from Webpacker

how to get work Fetch API with Rails and React.
Setup: Rails 5, Sprockets and React from Webpacker.
What I'm trying to achieve here is use Fetch API to fetch and load data to ReactBootstrapTable API.
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import 'whatwg-fetch'
class ExampleTable extends React.Component {
constructor() {
super();
this.state = {
datatable: [], // I'm not sure if I can use array to json data.
};
}
// I'm new to React, so I'm not sure if I'm passing props right
componentDidMount() {
console.log('start componentDidMount');
fetch('https://www.test.com/test.json')
.then(function(response) {
return response.json();
}).then(function(response) {
let datatable = response;
this.setStates({ datatable });
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
render() {
return (
<div>
<BootstrapTable
data={this.states.datatable} //Here, I'm passing data to the table
pagination
striped hover condensed
options={ { noDataText: 'Empty Table' } }>
<TableHeaderColumn isKey dataField='id' width='80px' dataAlign='center'>
ID
</TableHeaderColumn>
<TableHeaderColumn dataField='test'width='300px' dataAlign='left'>
Test
</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
export default ExampleTable;
The main problem here is that I'm not able to use Fetch API and also I'm not totally sure about the way I'm passing data to the table (basically how to use react)
I'm getting a error/warning from my IDE
fetch is not defined
And another error message from the Firefox console:
The above error occurred in the component: in ExampleTable
TypeError: this.states is undefined
I installed the Fetch API through yarn and checked the node_modules/whatwg-fetch folder. As described from the github API, I imported 'whatwg-fetch' as showed in the code above.
I don't know what else I should do. I installed ReactBoostrapTable in the same way and got succeeded doing it. Everything else is working fine.
I looked at the installation instructions of fetch for use with webpack, it says to add this to your webpack configuration:
entry: ['whatwg-fetch', ...]
Also, you mentioned the other error TypeError: this.states is undefined. It looks like you have a typo. In React, if you're trying to refer to state, you use it like this:
this.state.datatable
In your render method, you refer to this.states.
Also, when you're making your call with fetch, you're trying to call this.setStates. You should instead be using it like this:
this.setState({ somestate: "xyz"})

Electron app: How do you use ipcRenderer.sendToHost()?

In the Electron documentation for the webview tag, the following example is given to show how to communicate between the renderer process and the web page hosted in the webview:
With sendToHost method and ipc-message event you can easily communicate between guest page and embedder page:
// In embedder page.
const webview = document.getElementById('foo')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
// In guest page.
const {ipcRenderer} = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
However, in my guest web page (inside the webview), I get Uncaught ReferenceError: require is not defined when I try to require('electron'), as indicated in the docs.
Is there something else I need to do to be able to require the ipcRenderer module from the guest web page?
Electron version: 1.4.6
Note: I'm not sure if this is important or not, but the page running inside my webview is served from a local server. In my top-level page in the renderer process, I do something like: document.getElementById("webview").src = "http://localhost:1234/...";.
Edit: It looks like serving my web page from a local server does not change anything. I have the same error after trying with a static HTML file. It looks like the example in the docs simply doesn't work, or I'm understanding it wrong.
// Simple foo.html somewhere on my computer
<script>
const {ipcRenderer} = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
</script>
// In embedder page, in renderer process
document.getElementById("webview").src = "file://path/to/foo.html";
Output from the embedded page (inside the webview):
Uncaught ReferenceError: require is not defined
EDIT
For security reasons, the preferred way to use require in renderer processes is to use preload to inject only the minimum node integration your page requires. See point 2) of Electron's security recommendations. A minimal example for ipcRenderer:
// main.ts
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('https://my-website.com')
// preload.js
const { ipcRenderer } = require('electron')
window.sendToElectron= function (channel) {
ipcRenderer.send(channel)
}
In your webpage you can now use window.sendToElectron("ping").
If you're using <webview> inside the renderer process, you can use <webview src="page.html" preload="./preload.js" /> to achieve the same result. So, that's what I would use to answer my original question, and inside preload.js I would inject a function that calls ipcRenderer.sendToHost("pong") in the global window.
Old answer (bad for security)
I had missed a vital point in the webview docs. To be able to call require from the page embedded inside the webview, you need to set the nodeintegration attribute on the webview tag:
<webview id="webview" nodeintegration />

Knockout and jquery-ui\sortable Requirejs Configuration using CDN

I'm trying to load a lot of our JS dependencies using requirejs. We are having an issue with the dependency that KnockoutSortable has on jquery-ui\sortable.
I can not get sortable.js to come from the cdn download of jquery-ui it is satisfying it's dependency by downloading from the copy within my site. I have tried to shim
'knockoutSortable' : {
deps: ['jqueryUi']
},
but that has not forced Knockout to use the CDN downloaded version of jquery-ui
Our configuration is as follows:
var require = {
baseUrl: '/Scripts',
paths: {
jquery: ['//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min', 'lib/jquery-1.9.1.min'],
jqueryUi: ['//ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min', 'lib/jquery-ui-1.11.3.min'],
knockout: ['//cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min','lib/knockout-3.3.0.min'],
knockoutMapping: ['//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min','lib/knockout.mapping-latest.min'],
knockoutValidation: ['//cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.2/knockout.validation.min','lib/knockout.validation.min'],
knockoutPostBox: ['//cdnjs.cloudflare.com/ajax/libs/knockout-postbox/0.5.1/knockout-postbox.min', 'lib/knockout-postbox.min'],
knockoutSortable: ['//cdnjs.cloudflare.com/ajax/libs/knockout-sortable/0.11.0/knockout-sortable.min','lib/knockout-sortable.min'],
...
shim: {
'jquery': {
exports: '$'
},
'knockoutSortable' : {
deps: ['jqueryUi']
},...
Since jquery-ui and knockout both AMD compatible you can't use a shim configuration you need to use a map config instead to map jquery-ui modules back to the jqueryUi path.
See link
We solved this by adding this map configuration to the require.config
map : {
'*': {
'jquery-ui/core': 'jqueryUi',
'jquery-ui/sortable': 'jqueryUi',
'jquery-ui/draggable': 'jqueryUi',
'jquery-ui/mouse': 'jqueryUi',
'jquery-ui/widget': 'jqueryUi'
}
}

Dependency injection for Angular in Rails

The syntax for dependency injection in Angular.js is confusing me.
I have a Rails app that is using Angular. One of the directives needs to use the $cookies service. So I have the main Javascript file where I declare the angular app, and a directives folder with js-files for my directives.
So this is the relevant part of the main js file. I'm trying to inject the ngCookies module into it:
app.js
angular.module('myApp', [
'templates',
'ngCookies'
]);
and here is the file with the directive that needs the $cookies service:
my-directive.js
angular.module('myApp')
.directive("myDirective", ['$cookies', function(){
return {
restrict: 'E'
templateUrl: "my-directive-template.html",
scope: {
article: '=ngModel'
},
link: function(scope, element, attrs){
scope.myFunction = function(){
$cookies.example = "hello world"; // set a cookie
};
}
};
}]);
So I'm trying to inject the ngCookies module into the myApp module and then inject the $cookies service into the directive.
This syntax doesn't work; Firebug gives me an error: "Error: $cookies is undefined".
Could you please help me figure out how to inject dependencies in Angular properly?
Oh my! I guess the only thing I needed was to add the $cookies as an attribute for the function declaration as well so that the line
.directive("myDirective", ['$cookies', function(){
became
.directive("myDirective", ['$cookies', function($cookies){

Resources