jqGrid using requireJS - grid loads but does not work - javascript

I'm loading data into a jqGrid through requireJS, the data loads, formats and displays but after which nothing works, sorting, row selecting, paging etc. The grid works perfectly fine if I init the jqGrid without requireJS.
RequireJS config snippet :
"jqGrid": "jqGrid/jquery.jqGrid.min",
"grid-locale": "jqGrid/i18n/grid.locale-en", ...
shim: {
"jqGrid": ["grid-locale", "jquery-ui"]
}
JavaScript snippet:
define(["jquery", "httpUtils", "jqGrid"],
function ($, httpUtils, jqGrid) {
window.jqGrid = jqGrid;
var myViewModel = function () {
var data = httpUtils.httpSyncGet('xxx');
var grid = $('#index').jqGrid({
colNames: ['ClientIdentifier'],
colModel: [
{ name: 'ClientIdentifier', width: "150pt" }
],
datastr: data,
datatype: 'jsonstring',
rowNum: 25,
rownumbers: true,
height: 500,
viewrecords: true,
width: 1100,
shrinkToFit: false
});
};
return myViewModel;
});
Sorry if the code isn't very comprehensive I had to take out snippets from a large project. I'm just curious as to what causes the jqGrid to finish loading, but somehow 'unload' all of it's functions. There is no javascript error in the console as well.

I think you're missing some modules and dependencies. Here's what worked for me (and is also trimmed out from a larger project):
require.config({
baseUrl: "Scripts/TypeScript",
paths: {
jquerygrid: "../jquery.jqGrid.src",
jqueryui: "../jquery-ui-1.11.4",
jqgridlocale: "../i18n/grid.locale-en",
jqgrid: "../jquery.jqGrid.min"
},
shim: {
jqueryui: {
deps: ["jquery"]
},
uigrid: {
deps: ["jqueryui"]
},
jqgrid: {
deps: ['jqueryui', 'jqgridlocale']
},
jqgridlocale: {
deps: ['jqueryui']
}
}
});
I adapted the code above from this answer: requirejs jquery multiple dependent non module jquery plugins like jquery-ui and jqGrid , which addresses a more complicated scenario but my also be useful for you.

Related

How to inclue Jquery TimeEntry plugin with RequireJS

I am new working with requirejs, I have an old Asp.net Webform application that I am trying to apply some javascript module loading using requirejs. In this app I am using a jquery plugin named Time Entry, but is not working if I use requirejs, only works if I added the reference the old way. Here is my requirejs configuration and declaration.
In the aspx file:
<script src="../../scripts/require.js"></script>
<script>
require(["../../app/shared/require.config"],
function (config) {
require(["appIncidentTracking/incident-type-init"]);
});
</script>
My require.config file is like this:
require.config({
baseUrl: '../../scripts',
paths: {
app: '../../app/utilization-management',
appIncidentTracking: '../../app/incident-tracking',
jquery: 'jquery-3.1.1.min',
jqueryui: 'jquery-ui-1.12.1.min',
jqueryplugin: '../../js/jquery.plugin.min',
timeentry:'../../js/jquery.timeentry.min',
handlebars: 'handlebars.amd.min',
text: 'text',
moment: 'moment.min',
datatable: 'DataTables/jquery.dataTables.min',
blockUI: 'jquery.blockUI.min',
shared: '../../app/shared',
bootstrap: 'bootstrap.min',
'bootstrap-datepicker': 'bootstrap-datepicker.min',
'bootstrap-multiselect': '../js/bootstrap-multiselect/bootstrap-multiselect'
},
shim: {
bootstrap: {
deps: ['jquery']
},
'bootstrap-multiselect': {
deps: ['bootstrap']
},
timeentry: {
deps:['jquery', 'jqueryplugin']
}
}
});
and in my incident-type-init.js I only call the plugin:
/**
* Incident Type Init page
* #module incident-type-init
*/
define(function (require) {
var $ = require('jquery'),
jqueryplugin = require('jqueryplugin'),
timeentry = require('timeentry'),
bootstrap = require('bootstrap');
/**
* Jquery ready function
*/
$(function () {
$('.js-timeentry').timeEntry();
});
});
but when the application runs I got this error:
$.JQPlugin.createPlugin is not a function, it is like does not find the jquery.plugin.js
I checked the network tab in chrome and both files are loaded, jquery.plugin.js and jquery.timeentry.js
UPDATE: In our application, we are using Asp.net MasterPages, and there we are loading an old jquery version, 1.5.1, and I use that MasterPage in my page, but when I check the network tab in chrome, is loading the MasterPage scripts first,then all the requirejs stuff.
and the funniest part is that sometimes work, sometimes not.
Any clue?
The module jqueryplugin needs to have jQuery already loaded for it. It is not an AMD module because it does not call define. So you need an additional entry in shim for it:
jqueryplugin: ["jquery"]
The above is short for:
jqueryplugin: {
deps: ["jquery"]
}
I don't think your code is syntactically correct.
Try this:
1. Your script should refer to the require.config in data-main.
<script data-main="PATH_TO_CONFIG_FILE" src="../../scripts/require.js"></script>
2. Quotes are missing in paths of the config file. Instead it should be like this
require.config({
baseUrl: '../../scripts',
paths: {
"app": '../../app/utilization-management',
"appIncidentTracking": '../../app/incident-tracking',
"jquery": 'jquery-3.1.1.min',
"jqueryui": 'jquery-ui-1.12.1.min',
"jqueryplugin": '../../js/jquery.plugin.min',
"timeentry":'../../js/jquery.timeentry.min',
"handlebars": 'handlebars.amd.min',
"text": 'text',
"moment": 'moment.min',
"datatable": 'DataTables/jquery.dataTables.min',
"blockUI": 'jquery.blockUI.min',
"shared": '../../app/shared',
"bootstrap": 'bootstrap.min',
"bootstrap-datepicker": 'bootstrap-datepicker.min',
"bootstrap-multiselect": '../js/bootstrap-multiselect/bootstrap-multiselect'
},
shim: {
"bootstrap": {
deps: ["jquery"]
},
"bootstrap-multiselect": {
deps: ["bootstrap"]
},
"timeentry": {
deps:["jquery", "jqueryplugin"],
exports:"timeentry"
}
}
});
3. Since your module has dependencies, list them like this:
define(["jqueryplugin","timeentry","bootstrap"],function(jqueryplugin,timeentry,bootstrap) {
$(function () {
$('.js-timeentry').timeentry();
});
});

RequireJS - Issues loading Jquery and Jquery UI plugins

im new to requirejs and been loving it so far. I am in the process of implementing it to my existing project. I have a few jquery, Jquery UI and bootstrap plugins that all need to initialise at the start of the app.
I was hoping to put them all ligned up in a file called GDI_common.js and have it set in my main.js file in a require. When I load my page it seems to ignore my GDI_commons script. If I try to manually load the plugins via console they work fine.
I made sure that my dependencies are all correct and have what they need. Not quite sure what im overlooking at this point. Would anyone have any ideas or suggestions?
This is what my main.js file looks like:
require.config({
paths: {
"jqueryui": "../assets/jqueryUI/jquery-ui.min",
"bootstrap": "bootstrap.min",
"bootstrap_select": "../assets/silviomoreto-bootstrap-select-a8ed49e/dist/js/bootstrap-select.min",
"jqueryui_timepicker": "jquery-ui-timepicker-addon",
"jqueryui_timepicker_ext": "jquery-ui-sliderAccess",
"moment": "moment",
"cookie": "js.cookie",
"knockout-amd-helpers": "knockout-amd-helpers.min",
"text": "text"
},
"shim": {
bootstrap: {
deps : [ 'jquery'],
exports: 'Bootstrap'
},
bootstrap_select: {
deps : [ 'jquery', 'bootstrap'],
exports: 'Bootstrap_Select'
},
jqueryui_timepicker: {
deps : [ 'jquery','jqueryui'],
exports: 'JqueryUI_Timepicker'
},
jqueryui_timepicker_ext: {
deps : [ 'jquery','jqueryui'],
exports: 'Jqueryui_Timepicker_Ext'
}
}
});
require(["jquery","knockout", "XApplication", "Xcommon", "XButtons", "knockout-amd-helpers", "text", "moment"], function ($, ko, XApplication, GDI_common) {
ko.amdTemplateEngine.defaultPath = "../templates";
var viewmodel = new GDI_Application();
ko.applyBindings(viewmodel);
viewmodel.fetchdata();
});
This is what my my GDI_common file looks like:
define(["jquery", "jqueryui", "jqueryui_timepicker", "jqueryui_timepicker_ext", "moment", "bootstrap_select"], function($) {
//This loads the jqueryui_timepicker (jquery-ui-timepicker-addon.js) it needs jqueryui.
$('input[title^="Date de"]').datetimepicker({
addSliderAccess: true,
timeFormat: 'HH:mm',
dateFormat: "yy-mm-dd",
sliderAccessArgs: { touchonly: false }
});
//This loads the bootstrap-select plugin (bootstrap-select.min.js) it needs jquery and bootstrap.
$('.selectpicker').selectpicker();
//This is a jquery custom code that is used to calculate 2 fields upon clicking the .donne_moi_le_temps button.
$(".donne_moi_le_temps").click(function(){
updateDuration($('#DateDeDébut').val(), $('#DateDeFin').val());
function updateDuration(startTime, endTime) {
var ms = moment(endTime, 'YYYY/MM/DD HH:mm').diff(moment(startTime, 'YYYY/MM/DD HH:mm')),
dt = moment.duration(ms),
h = Math.floor(dt.asHours()),
m = moment.utc(ms).format('mm');
$('input[title^="Dur"]').val(h + ' heures, ' + m + ' minutes');
}
});
//This is loads the bootstrap tooltip function, this requires jquery and bootstrap.
$('[data-toggle="tooltip"]').tooltip();
//This is custom code and depends on the tooltip to be loaded first.
$(document).on('mouseenter', ".over_flow_control", function() {
var $this = $(this);
if(this.offsetWidth < this.scrollWidth && !$this.attr('title')) {
$this.tooltip({
title: $this.text(),
placement: "bottom",
container: 'body'
});
$this.tooltip('show');
}
});
});

RequireJS: CDN fallback not working with Kendo

Struggling to set up RequireJS with KendoUI over CDN and can't get fallback to work.
... from amazing burkeholland A Kendo UI ASP.NET MVC SPA Template
This what I begin with :
define([
'../Scripts/kendo/2014.1.416/kendo.router.min',
'../Scripts/kendo/2014.1.416/kendo.view.min',
'../Scripts/kendo/2014.1.416/kendo.fx.min'
], function () {
return kendo;
})
and it works fine.
If kendo.core.min is not defined, first statement in kendo.router says define(["./kendo.core.min"] and it is loaded from proper location.
However, when I try to use CDN with fallback location like this :
requirejs.config({
paths: {
'router': ['//cdn.kendostatic.com/2014.1.416/js/kendo.router.min', '../Scripts/kendo/2014.1.416/kendo.router.min'],
'view': ['//cdn.kendostatic.com/2014.1.416/js/kendo.view.min', '../Scripts/kendo/2014.1.416/kendo.view.min'],
'fx': ['//cdn.kendostatic.com/2014.1.416/js/kendo.fx.min', '../Scripts/kendo/2014.1.416/kendo.fx.min']
}
});
define([
'router',
'view',
'fx'
], function () {
return kendo;
});
requireJS tries to load kendo.core.min from baseUrl location, not fallback location.
Am I missing something?
However, if I try something like this :
requirejs.config({
paths: {
k: ['//cdn.kendostatic.com/2014.1.416/js', '../Scripts/kendo/2014.1.416']
}
});
define([
'k/kendo.router.min',
'k/kendo.view.min',
'k/kendo.fx.min'
], function () {
return kendo;
})
Fallback doesn't work at all... what am I missing?

Using TimelineJS and AMD

I'm looking for a way to use TimelineJS with RequireJS's implementation of AMD. I can get things partially working, e.g.
define(["storyjs", "timelinejs", ...], function(storyjs, timelinejs, ...) {
createStoryJS({
type: 'timeline',
width: '800',
height: '600',
source: { ... }, // sample JSON
embed_id: 'timeline-embed'
});
});
The above produces a timeline, but storyjs (which exports VMM in my RequireJS config) always attempts to perform its own loading of the TimelineJS libraries, which invariably produces errors in the Firebug/developer tools console.
I'm either looking for a way to programmatically build the TimelineJS object (which I couldn't find any examples of), tell StoryJS to not bother loading libs using its mechanism (because I've already provided them) and in general integrate TimelineJS with an AMD solution.
Any suggestions?
UPDATE:
RequireJS configuration used, below. For my own personal use I have a tendency to rename JS libraries and append their version numbers.
var require = {
waitSeconds: 5,
paths: {
"app": "../js/app"
// ** Libraries
,"backbone": "../js/lib/backbone-1.1.0.min"
,"bootstrap": "../js/lib/bootstrap-3.0.2.min"
,"jquery": "../js/lib/jquery-1.10.2.min"
,"jquery-ui": "../js/lib/jquery-ui-1.10.3.min"
,"json2": "../js/lib/json2"
,"underscore": "../js/lib/underscore-1.5.2.min"
// ** TimelineJS
,"storyjs": "../js/lib/storyjs-embed-2.0.3.min"
,"timelinejs": "../js/lib/timeline-2.26.3.min"
// ** RequireJS Plugins
,"domready": "../js/lib/plugins/requirejs/requirejs-plugin-domready-2.0.1"
,"i18n": "../js/lib/plugins/requirejs/requirejs-plugin-i18n-2.0.4"
,"text": "../js/lib/plugins/requirejs/requirejs-plugin-text-2.0.10"
},
shim: {
'backbone': { deps: ['underscore'], exports: 'Backbone' }
,'bootstrap': { deps: ['jquery'] }
,'jquery': { exports: '$' }
,'json2': { exports: 'JSON' }
,'storyjs': { exports: 'VMM' }
,'timelinejs': { deps: ['storyjs'] }
,'underscore': { exports: '_' }
}
};
It took digging into the TimelineJS source a bit to see what exactly createStoryJS was actually doing and then looking at some of the other source code, but I finally answered my own question. In fact, it is relatively straightforward and very similar to my early attempts to make this work before posting my question above to StackOverflow.
RequireJS Config:
// RequireJS config
var require = {
waitSeconds: 5,
paths: {
...
// ** TimelineJS
,"storyjs": "../js/lib/plugins/jquery/storyjs-embed-2.0.3.min"
,"timelinejs": "../js/lib/plugins/jquery/timeline-2.26.3.min"
...
},
shim: {
...
,'storyjs': { deps: ['jquery'], exports: 'VMM' }
,'timelinejs': { deps: ['jquery', 'storyjs'] }
...
}
};
Module instantiating TimelineJS object:
define([ "json2", "timelinejs"], function(JSON, timelinejs) {
var js_version = "2.24",
config = {
version: "2.24", // DEFAULT: 2.x
debug: true,
type: 'timeline',
source: {...} // Sample JSON
};
var timeline = new VMM.Timeline("timeline-embed", 800, 600);
timeline.init(config);
});
This is, at the very least, one example for handling the TimelineJS instantiation using RequireJS/AMD; it is also how I've decided to solve my original issue.

Require.js Error: Load timeout for modules: backbone,jquerymobile

I am trying to use r.js to optimize my code but I keep running to this error:
Tracing dependencies for: init
Error: Load timeout for modules: backbone,jquerymobile
The command I am running is this:
$ java -classpath /Users/dixond/build-tools/rhino1_7R4/js.jar:/Users/dixond/build-tools/closurecompiler/compiler.jar org.mozilla.javascript.tools.shell.Main /Users/dixond/build-tools/r.js/dist/r.js -o /Users/dixond/Sites/omm_mobile/js/build.js
My build.js file looks like this:
( {
//appDir: "some/path/",
baseUrl : ".",
mainConfigFile : 'init.js',
paths : {
jquery : 'libs/jquery-1.8.3.min',
backbone : 'libs/backbone.0.9.9',
underscore : 'libs/underscore-1.4.3',
json2 : 'libs/json2',
jquerymobile : 'libs/jquery.mobile-1.2.0.min'
},
packages : [],
shim : {
jquery : {
exports : 'jQuery'
},
jquerymobile : {
deps : ['jquery'],
exports : 'jQuery.mobile'
},
underscore : {
exports : '_'
},
backbone : {
deps : ['jquerymobile', 'jquery', 'underscore'],
exports : 'Backbone'
}
},
keepBuildDir : true,
locale : "en-us",
optimize : "closure",
skipDirOptimize : false,
generateSourceMaps : false,
normalizeDirDefines : "skip",
uglify : {
toplevel : true,
ascii_only : true,
beautify : true,
max_line_length : 1000,
defines : {
DEBUG : ['name', 'false']
},
no_mangle : true
},
uglify2 : {},
closure : {
CompilerOptions : {},
CompilationLevel : 'SIMPLE_OPTIMIZATIONS',
loggingLevel : 'WARNING'
},
cssImportIgnore : null,
inlineText : true,
useStrict : false,
pragmas : {
fooExclude : true
},
pragmasOnSave : {
//Just an example
excludeCoffeeScript : true
},
has : {
'function-bind' : true,
'string-trim' : false
},
hasOnSave : {
'function-bind' : true,
'string-trim' : false
},
//namespace: 'foo',
skipPragmas : false,
skipModuleInsertion : false,
optimizeAllPluginResources : false,
findNestedDependencies : false,
removeCombined : false,
name : "init",
out : "main-built.js",
wrap : {
start : "(function() {",
end : "}());"
},
preserveLicenseComments : true,
logLevel : 0,
cjsTranslate : true,
useSourceUrl : true
})
And my init.js looks like this:
requirejs.config({
//libraries
paths: {
jquery: 'libs/jquery-1.8.3.min',
backbone: 'libs/backbone.0.9.9',
underscore: 'libs/underscore-1.4.3',
json2 : 'libs/json2',
jquerymobile: 'libs/jquery.mobile-1.2.0.min'
},
//shimming enables loading non-AMD modules
//define dependencies and an export object
shim: {
jquerymobile: {
deps: ['jquery'],
exports: 'jQuery.mobile'
},
underscore: {
exports: '_'
},
backbone: {
deps: ['jquerymobile', 'jquery', 'underscore', 'json2'],
exports: 'Backbone'
}
}
});
requirejs(["backbone",], function(Backbone) {
//Execute code here
});
What am I doing wrong in this build process?
Require.js has a Config option called waitSeconds. This may help.
RequireJS waitSeconds
Here's an example where waitSeconds is used:
requirejs.config({
baseUrl: "scripts",
enforceDefine: true,
urlArgs: "bust=" + (new Date()).getTime(),
waitSeconds: 200,
paths: {
"jquery": "libs/jquery-1.8.3",
"underscore": "libs/underscore",
"backbone": "libs/backbone"
},
shim: {
"underscore": {
deps: [],
exports: "_"
},
"backbone": {
deps: ["jquery", "underscore"],
exports: "Backbone"
},
}
});
define(["jquery", "underscore", "backbone"],
function ($, _, Backbone) {
console.log("Test output");
console.log("$: " + typeof $);
console.log("_: " + typeof _);
console.log("Backbone: " + typeof Backbone);
}
);
The Error
I recently had a very similar issue with an angularJS project using requireJS.
I'm using Chrome canary build (Version 34.0.1801.0 canary) but also had a stable version installed (Version 32.0.1700.77) showing the exact same issue when loading the app with Developer console open:
Uncaught Error: Load timeout for modules
The developer console is key here since I didn't get the error when the console wasn't open. I tried resetting all chrome settings, uninstalling any plugin, ... nothing helped so far.
The Solution
The big pointer was a Google group discussion (see resources below) about the waitSeconds config option. Setting that to 0 solved my issue. I wouldn't check this in since this just sets the timeout to infinite. But as a fix during development this is just fine. Example config:
<script src="scripts/require.js"></script>
<script>
require.config({
baseUrl: "/another/path",
paths: {
"some": "some/v1.0"
},
waitSeconds: 0
});
require( ["some/module", "my/module", "a.js", "b.js"],
function(someModule, myModule) {
//This function will be called when all the dependencies
//listed above are loaded. Note that this function could
//be called before the page is loaded.
//This callback is optional.
}
);
</script>
Most common other causes for this error are:
errors in modules
wrong paths in configuration (check paths and baseUrl option)
double entry in config
More Resources
Troubleshooting page from requireJS: http://requirejs.org/docs/errors.html#timeout point 2, 3 and 4 can be of interest.
Similar SO question: Ripple - Uncaught Error: Load timeout for modules: app http://requirejs.org/docs/errors.html#timeout
A related Google groups discussion: https://groups.google.com/forum/#!topic/requirejs/70HQXxNylYg
In case others have this issue and still struggling with it (like I was), this problem can also arise from circular dependencies, e.g. A depends on B, and B depends on A.
The RequireJS docs don't mention that circular dependencies can cause the "Load timeout" error, but I've now observed it for two different circular dependencies.
Default value for waitSeconds = 7 (7 seconds)
If set to 0, timeout is completely disabled.
src: http://requirejs.org/docs/api.html
The reason for the issue is that Require.js runs into the timeout since the project might have dependencies to large libraries. The default timeout is 7 seconds. Increasing the value for this config option (called waitSeconds) solves it of course but it is not the right approach.
Correct approach would be to improve the page loading time. One of the best technics to speed up a page loading is minification - the process of compressing the code. There are some good tools for minification like r.js or webpack.
I only get this error when running tests on Mobile Safari 6.0.0 (iOS 6.1.4). waitSeconds: 0 has given me a successful build for now. I'll update if my build fails on this again
TLDR:
Requiring the same file twice with two valid different names, possibly two of the following:
absolute path: '/path/to/file.js'
relative path: './path/to/file.js'
as a module: 'path/to/file'
as a module on main paths config:
paths: {
'my/module/file' : '/path/to/file'
}
Recently had this same issue. I did change some require paths in bulk so I knew the issue was about that.
I could clearly see on both server side logs and network debugging tab the file being served in less than a second. It was not a real timeout issue.
I tried to use xrayrequire as suggested to find any circular dependency without success. I looked for requires of the conflicting file and found out I was requiring it twice with different names.

Categories