Polymer 1.0 : How to configure jshint for Polymer behaviours? - polymer

I have a globalize-behaviour.html file:
<script>
GlobalizeBehavior = {
// https://www.polymer-project.org/1.0/docs/devguide/behaviors.html#definining-behaviors
i18n: function(key) {
return key;
}
};
</script>
I am including this file in other custom-elements like this:
<link rel="import" href="../globalize-behavior/globalize-behavior.html">
and using it like so (in global-element.html):
<script>
(function() {
Polymer({
is: 'global-element',
behaviors: [GlobalizeBehavior],
openAddTransDialog: function() {},
});
})();
</script>
And, here's the .jshintrc file:
{
"node": true,
"browser": true,
"esnext": true,
"bitwise": true,
"camelcase": true,
"curly": true,
"eqeqeq": true,
"immed": true,
"indent": 2,
"latedef": true,
"noarg": true,
"quotmark": "single",
"undef": true,
"unused": true,
"globals": {
"wrap": true,
"unwrap": true,
"Polymer": true,
"Platform": true,
"page": true,
"app": true
}
}
I am getting following error while running jshint:
globalize-behavior.html line 2 col 1 'GlobalizeBehavior' is not defined.
global-element.html line 104 col 17 'GlobalizeBehavior' is not defined.
How can I fix this?

You could add
"globals": {
"GlobalizeBehavior": true
}
or:
"predef": [
"GlobalizeBehavior"
]
to your .jshintrc file?

Related

Eslint fix command is not fixing all of the vue/html-indent errors

I have some linting rules in my .eslintrc.js which looks like the following:
module.exports = {
root: true,
env: {
browser: true,
es6: true,
node: true,
},
extends: ['plugin:vue/recommended', 'eslint:recommended'],
parserOptions: {
parser: 'babel-eslint',
},
rules: {
'import/extensions': 0,
'import/no-unresolved': 0,
'import/prefer-default-export': 0,
'no-shadow': 0, // TODO: figure out this error in vuex state
'no-param-reassign': 0, // TODO: figure out this error in vuex state
'no-use-before-define': 0, // TODO: figure out this error in vuex state
'no-underscore-dangle': 0,
'no-useless-escape': 0,
semi: [2, 'never'],
'vue/no-v-html': 0,
'vue/custom-event-name-casing': 0,
'vue/html-indent': [
'error',
4,
{
attribute: 1,
baseIndent: 1,
closeBracket: 0,
alignAttributesVertically: true,
ignores: [],
},
],
'vue/script-indent': [
'error',
2,
{
baseIndent: 1,
switchCase: 1,
ignores: [],
},
],
'vue/max-attributes-per-line': [
'error',
{
singleline: 1,
multiline: {
max: 1,
allowFirstLine: true,
},
},
],
'vue/html-closing-bracket-newline': [
'error',
{
singleline: 'never',
multiline: 'never',
},
],
'vue/html-self-closing': [
'error',
{
html: {
void: 'always',
normal: 'always',
component: 'always',
},
svg: 'always',
math: 'always',
},
],
'vue/attribute-hyphenation': ['error', 'always'],
},
}
I have these setup as my workspace settings:
{
"editor.tabSize": 4,
"editor.insertSpaces": false,
"editor.detectIndentation": false,
"vetur.format.options.useTabs": false,
"vetur.format.defaultFormatterOptions": {
"prettyhtml": {
"printWidth": 120,
"singleQuote": true
},
"js-beautify-html": {
"wrap_attributes": "force-aligned",
"indent_size": 4
}
},
"vetur.format.scriptInitialIndent": true,
"vetur.format.styleInitialIndent": true,
"vetur.format.defaultFormatter.js": "prettier-eslint",
"vetur.format.defaultFormatter.html": "js-beautify-html",
"html.format.wrapAttributes": "force",
"vetur.format.defaultFormatter.css": "none",
"vetur.format.defaultFormatter.scss": "prettier",
"editor.formatOnSave": true,
"vetur.validation.template": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
When I save a file and format everything works fine, the formatting works. But when I run
eslint --fix --ext js,vue src
This shows the lint warnings and errors, but doesn't comply with the vue/html-indent rule.
If the component looks like this:
<transition
name="slide-fade"
mode="in-out">
<div
v-if="showDesktopSearch"
v-on-clickaway="away"
class="desktop-search-component"
:class="positionClass">
This is the body
</div>
</transition>
If I save the component looks like this:
<transition name="slide-fade"
mode="in-out">
<div v-if="showDesktopSearch"
v-on-clickaway="away"
class="desktop-search-component"
:class="positionClass">
This is the body
</div>
</transition>
But if I run the linting command, it looks like this:
<transition
name="slide-fade"
mode="in-out">
<div
v-if="showDesktopSearch"
v-on-clickaway="away"
class="desktop-search-component"
:class="positionClass">
This is the body
</div>
</transition>
I want to fix all of the vue/html-indent errors when running the lint command, but I have been unsuccessful here. How can I get the vetur/eslint format from cli?
This is my .eslintrc.js
module.exports = {
root: true,
env: {
node: true,
browser: true,
},
extends: ['plugin:vue/essential', 'plugin:prettier/recommended', '#vue/prettier'],
rules: {
'eqeqeq': 'off',
'no-plusplus': 'off',
"no-return-assign": "off",
'max-len': ['error', { code: 120, ignoreUrls: true, ignoreComments: true }],
'linebreak-style': 0,
'vue/max-attributes-per-line': 'off',
'vue/component-name-in-template-casing': ['error', 'PascalCase'],
'no-console': 'off',
'no-restricted-syntax': [
'error',
{
selector:
"CallExpression[callee.object.name='console'][callee.property.name!=/^(log|warn|error|info|trace)$/]",
message: 'Unexpected property on console object was called',
},
],
},
parserOptions: {
parser: 'babel-eslint',
},
};
And .prettierrc
{
"semi": true,
"tabWidth": 2,
"useTabs": false,
"printWidth": 100,
"singleQuote": true,
"editor.insertSpaces": true,
"trailingComma": "all",
"bracketSpacing": true,
"jsxBracketSameLine": true,
"arrowParens": "always"
}
And vue.config.js
module.exports = {
devServer: {
host: '0.0.0.0',
port: 3201,
https: false,
disableHostCheck: true,
},
runtimeCompiler: true,
chainWebpack: (config) => {
config.module
.rule('eslint')
.use('eslint-loader')
.options({
fix: true,
});
},
pluginOptions: {
apollo: {
enableMocks: true,
enableEngine: false,
// Cross-Origin options
cors: '*',
},
},
};

Gulp cannot parse .hintrc file

When running this Gulp task
var gulp = require('gulp'),
util = require('gulp-util'), // For logging
print = require('gulp-print'), // For logging
jshint = require('gulp-jshint');
gulp.task('analyse', function () {
log('Analyzing source with JSHint')
gulp.src(paths.jsContent)
.pipe(print())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish', { verbose: true }))
.pipe(jshint.reporter('fail'));
});
I get this output:
[14:43:26] Starting 'analyse'...
[14:43:26] Analyzing source with JSHint
[14:43:26] Finished 'analyse' after 32 ms
[gulp] Scripts\main.js
ERROR: Can't parse config file: C:\MyProject\src\MyProject.jshintrc
Error:SyntaxError: Unexpected token
The Gulp file I use is from https://raw.githubusercontent.com/johnpapa/pluralsight-gulp/master/.jshintrc and looks like:
{
"bitwise": true,
"camelcase": true,
"curly": true,
"eqeqeq": true,
"es3": false,
"forin": true,
"freeze": true,
"immed": true,
"indent": 4,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"noempty": true,
"nonbsp": true,
"nonew": true,
"plusplus": false,
"quotmark": "single",
"undef": true,
"unused": false,
"strict": false,
"maxparams": 10,
"maxdepth": 5,
"maxstatements": 40,
"maxcomplexity": 8,
"maxlen": 120,
"asi": false,
"boss": false,
"debug": false,
"eqnull": true,
"esnext": false,
"evil": false,
"expr": false,
"funcscope": false,
"globalstrict": false,
"iterator": false,
"lastsemic": false,
"laxbreak": false,
"laxcomma": false,
"loopfunc": true,
"maxerr": 50,
"moz": false,
"multistr": false,
"notypeof": false,
"proto": false,
"scripturl": false,
"shadow": false,
"sub": true,
"supernew": false,
"validthis": false,
"noyield": false,
"browser": true,
"node": true,
"globals": {
"angular": false
}
}
Can this be solved?
Just replace your .jshintrc file with the original from John's repo and you will be fine.

How to use native date picker in both form and row editing in free jqgrid

Browser native datepicker is used for inline row editing as described in How to use input type='date' for date column in jqGrid
How to use it for form editing also?
I tried code below:
Selected row in grid
Pressed edit button in toolbar
Pressed save button in edit form
After that date disappears from grid invdate column.
Also pressing next and previous record buttons in edit form cause invdate to disappear.
How to edit and show date in edit form using browser native html5 date type picker if it is supported in browser ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>https://stackoverflow.com/q/26040738/315935</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="author" content="Oleg Kiriljuk"/>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.4/themes/redmond/jquery-ui.css"/>
<link rel="stylesheet" type="text/css" href="http://cdn.jsdelivr.net/free-jqgrid/4.8.0/css/ui.jqgrid.css"/>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<style type="text/css">
html, body { font-size: 75%; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/free-jqgrid/4.8.0/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/free-jqgrid/4.8.0/js/jquery.jqgrid.src.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<script type="text/javascript">
//<![CDATA[
/*global $,Modernizr */
/*jslint browser: true, unparam: true */
$(function () {
"use strict";
var mydata = [
{ id: "10", invdate: "", name: "test1", note: "note1", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "20", invdate: "2007-10-02", name: "test2", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
{ id: "30", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
{ id: "40", invdate: "2007-10-04", name: "test4", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "50", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }
],
$grid = $("#list"),
initDateEdit = function (elem, options) {
// we need get the value before changing the type
var orgValue = $(elem).val(), newformat,
cm = $(this).jqGrid("getColProp", options.name);
$(elem).attr("type", "date");
if ((Modernizr && !Modernizr.inputtypes.date) || $(elem).prop("type") !== "date") {
// if type="date" is not supported call jQuery UI datepicker
$(elem).css({ width: "8em" }).datepicker({
dateFormat: "mm/dd/yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
} else {
// convert date to ISO
if (orgValue !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$(this).jqGrid("getGridRes", "formatter.date.newformat");
$(elem).val($.jgrid.parseDate.call(this, newformat, orgValue, "Y-m-d"));
}
// "10em" is better for Chrome and "11em" for Opera 24
$(elem).css("width", /OPR/.test(navigator.userAgent) ? "11em" : "10em");
}
},
myBeforeSaveRow = function (options, rowid) {
var $self = $(this), $dates = $("#" + $.jgrid.jqID(rowid)).find("input[type=date]");
$dates.each(function () {
var $this = $(this), newformat, str,
id = $this.attr("id"),
colName = id.substr(rowid.length + 1),
cm = $self.jqGrid("getColProp", colName);
if ((Modernizr && Modernizr.inputtypes.date) || $this.prop("type") === "date") {
// convert from iso to newformat
str = $this.val();
if (str !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$self.jqGrid("getGridRes", "formatter.date.newformat");
str = $.jgrid.parseDate.call($self[0], "Y-m-d", str, newformat);
}
$this.attr("type", "text");
$this.val(str);
}
});
},
initDateSearch = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: "mm/dd/yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showWeek: true,
showButtonPanel: true
});
}, 50);
},
numberTemplate = {formatter: "number", align: "right", sorttype: "number",
editrules: {number: true, required: true},
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"] }};
$grid.jqGrid({
datatype: "local",
//loadComplete: function() {
// $grid.jqGrid('setGridParam', { datatype: 'json' });
//},
data: mydata,
colNames: ["Client", "Date", "Closed", "Shipped via", "Notes", "Tax", "Amount", "Total"],
colModel: [
{ name: "name", align: "center", editable: true, width: 65, editrules: {required: true} },
{ name: "invdate", width: 125, align: "center", sorttype: "date",
formatter: "date", /*formatoptions: { newformat: "m/d/Y"},*/ editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch } },
{ name: "closed", width: 70, align: "center", editable: true, formatter: "checkbox",
edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"},
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" } },
{ name: "ship_via", width: 105, align: "center", editable: true, formatter: "select",
edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT;IN:Intim", defaultValue: "IN" },
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;FE:FedEx;TN:TNT;IN:IN" } },
{ name: "note", width: 60, sortable: false, editable: true, edittype: "textarea" },
{ name: "tax", width: 52, editable: true, template: numberTemplate },
{ name: "amount", width: 75, editable: true, template: numberTemplate },
{ name: "total", width: 60, template: numberTemplate }
],
rowNum: 10,
rowList: [5, 10, 20],
iconSet: "fontAwesome",
pager: "#pager",
gridview: true,
autoencode: true,
ignoreCase: true,
sortname: "invdate",
viewrecords: true,
sortorder: "desc",
height: "auto",
rownumbers: true,
editurl: "clientArray",
//editurl: "http://cdn.jsdelivr.net/test",
toppager: true,
onSelectRow: function (rowid) {
var $self = $(this),
savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, {
keys: true,
beforeSaveRow: myBeforeSaveRow
});
}
});
$.extend(true,$.jgrid.edit, {
closeAfterAdd: true,
navkeys: [true,33,34],
savekey: [true, 13],
recreateForm: true,
reloadAfterSubmit: false,
left: 10,
top: 15,
dataheight: '100%',
width: window.innerWidth - 18
});
$grid.jqGrid("navGrid", "#list_toppager", {
edit: true
});
});
//]]>
</script>
</head>
<body>
<table id="list"><tr><td></td></tr></table>
<div id="pager"></div>
</body>
</html>
The workaround used in myBeforeSaveRow need be implemented in form editing too. Instead of that I changed the code of free jqGrid so that you **don't need to use beforeSaveRow: myBeforeSaveRow at all. I adjusted the code of inline editing and form editing so that it works correctly on saving the data from <input type="date">. One should be only careful and set the value of type to text if type="date" is not supported.
The demo uses the current code of free jqGrid from GitHub. I tested the demo in Chrome 41, Opera 28 where <input type="date"> is supported. I tested the changes in Safari 5.1.7, Firefox 37 and IE 10. The demo works here too. It use the following modified code of initDateEdit:
var initDateEdit = function (elem, options) {
// we need get the value before changing the type
var orgValue = $(elem).val(), newformat,
cm = $(this).jqGrid("getColProp", options.name);
$(elem).attr("type", "date");
if ((typeof Modernizr !== "undefined" && !Modernizr.inputtypes.date) || $(elem).prop("type") !== "date") {
$(elem).attr("type", "text"); // !!! important to make saving works correctly
$(elem).css({ width: "8em" }).datepicker({
dateFormat: "mm/dd/yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
} else {
// convert date to ISO
if (orgValue !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$(this).jqGrid("getGridRes", "formatter.date.newformat");
$(elem).val($.jgrid.parseDate.call(this, newformat, orgValue, "Y-m-d"));
}
$(elem).css({width: "11em"});
}
};
The other code of inline and form editing is the standard:
...
onSelectRow: function (rowid) {
var $self = $(this),
savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid);
},
inlineEditing: {
keys: true
}
}).jqGrid("navGrid").jqGrid("inlineNav");
The options beforeSaveRow: myBeforeSaveRow are removed.

Extjs, can't read a simple json inside a treepanel

I am in trouble trying to load a very simple json where nodes are nested inside "data" as showed below. I expect to get two nodes with text AAA and BBB, but I only get a tree with a couple of empty nodes with infinite children (each children with a single sub children).
test_lrymgr.json
{
"data": [
{
"text": ".",
"children": [
{
"nodename": "AAA",
"isvisible": true,
"expanded": false
},
{
"nodename": "BBB",
"isvisible": true,
"expanded": false
}
]
}
],
"metadata": { "success":true, "msg":"", "totalCount":1, "totalPages":1, "prevLink":"", "nextLink":""}
}
test_lrymgr.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="ext/packages/ext-theme-classic/build/resources/ext-theme-classic-all.css" />
<script type="text/javascript" src="ext/ext-all-debug.js"></script>
</head>
<body>
<script type="text/javascript">
Ext.onReady(function () {
try {
//define model
Ext.define('MyDataModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'nodename', mapping: 'nodename' },
{ name: 'isvisible', mapping: 'isvisible' }
],
});
//define store
Ext.define('MyStore', {
extend: 'Ext.data.TreeStore',
storeId: 'idStoreLryManager',
model: 'MyDataModel',
proxy: {
type: 'ajax',
url: 'test_lrymgr.json',
reader: {
type: 'json',
root: 'data',
metaProperty: 'metadata',
totalProperty: 'metadata.totalCount',
successProperty: 'metadata.success',
messageProperty: 'metadata.msg'
},
}
});
//define tree panel
Ext.define('MyTreePanel', {
extend: 'Ext.tree.Panel',
alias: 'widget.myTreePanel',
store: 'MyStore',
rootVisible: false,
columns: [
{
xtype: 'treecolumn',
dataIndex: 'nodename',
sortable: false,
flex: 2,
header: ''
},
{
xtype: 'checkcolumn',
dataIndex: 'isvisible',
sortable: false,
width: 55,
header: 'Visible'
}
]
});
//create tree view
var storeInstance = Ext.create('MyStore');
Ext.createWidget('window', {
title: 'test',
layout: 'fit',
autoShow: true,
height: 360,
width: 200,
items: {
xtype: 'myTreePanel',
store: storeInstance,
border: false
}
});
//load
storeInstance.load({
scope: storeInstance,
callback: function (records, operation, success) {
try {
}
catch (ex) {
Ext.Msg.alert("", "callback error: " + ex);
}
}
});
}
catch (ex)
{
Ext.Msg.alert("", ex)
}
});
</script>
</body>
</html>
Any idea about what's wrong?...
Your json over here is wrong.Root mentioned in the store is "data".So
your json should be something like this:
{
"data": [{
"nodename": "child1",
"data": [{
"nodename": "subChild1",
"expanded": false,
"leaf": true
}, {
"nodename": "subChild2",
"expanded": false,
"leaf": true
}]
}],
"metadata": {
"success": true,
"msg": "",
"totalCount": 1,
"totalPages": 1,
"prevLink": "",
"nextLink": ""
}
}
For the tree to read nested data, the Ext.data.reader.Reader must be configured with a root property, so the reader can find nested data for each node (if a root is not specified, it will default to 'children'). This will tell the tree to look for any nested tree nodes by the same keyword, i.e., 'children'. If a root is specified in the config make sure that any nested nodes with children have the same name. Note that setting defaultRootProperty accomplishes the same thing.
You can see the simples possible tree configuration here: http://extjs.eu/ext-examples/#tree-simplest

how to display jqgrid from url (local data works, url data does not)

I have looked various question/answers on stackoverflow, but haven't found a solution.
When I use the first block of jqgrid code (data is local), the table and the data are displayed.
When I use the second block (data loaded from url), an empty table is displayed.
The strange part is that the local data is the actual content of the url file.
So I had assumed that the behavior would be identical.
Why can I not display the data using the url,
when the same data, if copied into the code, is displayed?
The HTML (calls mytest.js which contains the jqgrid code):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.8.23.custom.css" />
<link rel="stylesheet" href="ui.jqgrid.css" />
<script src="jquery-1.8.0.min.js"></script>
<script src="jquery-ui-1.8.23.custom.min.js"></script>
<script src="grid.locale-en.js"></script>
<script src="jquery.jqGrid.min.js"></script>
<script src="mytest.js" type="text/javascript"></script>
</head>
<body>
<h1>hey</h1>
<table id="jqgrid"></table>
</body>
</html>
JSON as local data (data displays, [here, edited for brevity]):
var mydata = [
{"_id": {"$oid": "50a3f962b7718da1a3090fa9"},
"config": {"titlepage":
{"title": "My First Title",
"color": true,
"fontsize": "42/44",
}
}
},
{"_id": {"$oid": "50a3f962b7718da1a3090faa"},
"config": {"titlepage":
{"title": "My Second Title",
"color": true,
"fontsize": "42/44",
}
}
}
];
jQuery(document).ready(function(){
$('#jqgrid').jqGrid({
datatype: 'local',
data: mydata,
jsonReader: {
repeatitems : false,
},
caption: 'Titlepage Parameters',
colNames: ['title', 'color','fontsize'],
colModel: [
{name: 'config.titlepage.title'},
{name: 'config.titlepage.color'},
{name: 'config.titlepage.fontsize'},
],
});
});
JSON via URL (no data displayed). The file mydata.json contains the same data
that is used above, but in a local file instead of in the actual js code:
jQuery(document).ready(function(){
$('#jqgrid').jqGrid({
url:'mydata.json',
datatype:"json",
jsonReader: {
repeatitems : false,
},
caption: 'Titlepage Parameters',
colNames: ['title', 'color','fontsize'],
colModel: [
{name: 'config.titlepage.title'},
{name: 'config.titlepage.color'},
{name: 'config.titlepage.fontsize'},
],
});
});
First of all I would fix a little your first version of working code. jsonReader will be not used if you use jsonReader. Instead of that it will be used localReader. Additionally I would recommend you always use native id values if the input data have such one. So I would fix the code to the following:
$(function () {
"use strict";
var mydata = [
{
"_id": {"$oid": "50a3f962b7718da1a3090fa9"},
"config": {
"titlepage": {
"title": "My First Title",
"color": true,
"fontsize": "42/44"
}
}
},
{
"_id": {"$oid": "50a3f962b7718da1a3090faa"},
"config": {
"titlepage": {
"title": "My Second Title",
"color": true,
"fontsize": "42/44"
}
}
}
];
$('#jqgrid').jqGrid({
datatype: 'local',
data: mydata,
caption: 'Titlepage Parameters',
gridview: true,
height: 'auto',
colNames: ['title', 'color', 'fontsize'],
colModel: [
{name: 'config.titlepage.title' },
{name: 'config.titlepage.color' },
{name: 'config.titlepage.fontsize' },
],
localReader: {
id: "_id.$oid"
}
});
});
See the first demo.
In case of usage datatype: "json" you need to fix the jsonReader:
$(function () {
"use strict";
$('#jqgrid').jqGrid({
datatype: 'json',
url: 'Tim2.json',
caption: 'Titlepage Parameters',
gridview: true,
height: "auto",
//colNames: ['title', 'color', 'fontsize'],
colModel: [
{name: 'title', jsonmap: 'config.titlepage.title' },
{name: 'color', jsonmap: 'config.titlepage.color' },
{name: 'fontsize', jsonmap: 'config.titlepage.fontsize' },
],
jsonReader: {
repeatitems: false,
id: "_id.$oid",
root: function (obj) {
return obj;
}
}
});
});
See another demo.
Oleg's answer is the full solution.
Here is the modified code which works. That is, the code I originally wrote plus the one change (from Oleg) that successfully loaded the data into the grid. The key for me was to add the root function in jsonReader:
jQuery(document).ready(function(){
$('#jqgrid').jqGrid({
url:'mydata.json',
datatype:"json",
jsonReader: {
root: function (obj) { return obj; },
repeatitems : false,
},
caption: 'Titlepage Parameters',
colNames: ['title', 'color','fontsize'],
colModel: [
{name: 'config.titlepage.title'},
{name: 'config.titlepage.color'},
{name: 'config.titlepage.fontsize'},
],
});
});