I am using jstree and select_node.jstree wont fire, here is the code
$(document).ready(function () {
//$("#MySplitter").splitter();
setupSplitter();
$("#divJsTreeDemo").jstree({
"themes": {
"theme": "default",
"dots": false,
"icons": false
},
"plugins": [
"core", "themes", "json_data", "ui", "types"
],
"types": {
// I set both options to -2, as I do not need depth and children count checking
// Those two checks may slow jstree a lot, so use only when needed
"max_depth": -2,
"max_children": -2,
// I want only `drive` nodes to be root nodes
// This will prevent moving or creating any other type as a root node
"valid_children": ["drive"],
"types": {
// The default type
"default": {
// I want this type to have no children (so only leaf nodes)
// In my case - those are files
"valid_children": "none",
// If we specify an icon for the default type it WILL OVERRIDE the theme icons
"icon": {
"image": "../../Repository/Images/file.png"
}
},
// The `folder` type
"folder": {
// can have files and other folders inside of it, but NOT `drive` nodes
"valid_children": ["default", "folder"],
"icon": {
"image": "../../Repository/Images/folder.png"
}
}
}
},
"json_data": {
"ajax": {
"type": "POST",
"url": "GetTreeNodes",
"data": function (n) {
var myJSONText = JSON.stringify({ id: n.attr ? n.attr("id").replace("node", "") : 0 }, replacer);
return { id: n.attr ? n.attr("id").replace("node", "") : 0 };
},
"success": function (data) {
$(".folder-file-container").remove();
RenderFileFolder(data);
}
}
// "data": {
// // `data` can also be an object
// "data": {
// "title": "The node title",
// // omit when not needed
// "attr": {},
// // if `icon` contains a slash / it is treated as a file, used for background
// // otherwise - it is added as a class to the <ins> node
// "icon": "../../Repository/Images/pdf.png"
// },
// // the `metadata` property will be saved using the jQuery `data` function on the `li` node
// }
}
}).bind("select_node.jstree", function (e, data) {
alert(data.rslt.obj.data("id"));
});
});
Try this instead:
.bind("select_node.jstree", function (e, data) {
var a = $.jstree._focused().get_selected();
alert(a);
}
(taken from jstree select node).
Related
This is the start of the object. I should be able to get the elements of celldata.values.
var generatedObj1 = {
"agg": "Glossar",
"ifa": null,
"ifv": null,
"ird": null,
"afv": null,
"ard": null,
"metaData": {
"cellMetaDataList": [{
"cell": "glossar", // <-- cell type
"cmv": null,
"crd": null,
"logicalData": {
"body": [{
"id": "f5d", // <-- body id 1
"name": "name", // <-- attribute name 1
"minLength": 3,
"maxLength": 100,
"minValue": null,
"maxValue": null,
"wertebereich": "ALPHANUMERISCH",
"validationCode": "",
"exampleValues": ["Langer Name", "Kurzer Name", "Kein Name"]
},
{
"id": "42", // <-- body id 2
"name": "kurzname", // <-- attribute name 2
"minLength": 3,
"maxLength": 20,
"minValue": null,
"maxValue": null,
"wertebereich": "ALPHANUMERISCH",
"validationCode": "",
"exampleValues": ["long_desc", "short_desc", "no_desc"]
},
{
"id": "9d", // <-- body id 3
"name": "eindeutig", // <-- attribute name 3
"minLength": 1,
"maxLength": 1,
"minValue": null,
"maxValue": null,
"wertebereich": "WAHRHEITSWERT",
"validationCode": "",
"exampleValues": [true, false]
}
]
}
}]
},
"data": {
"cellData": [{ // row 1 from res1
"cell": "glossar", // <-- cell type
"id": "5b", // <- UUID v4 (generated by the function)
"cmv": null,
"crd": null,
"caption": {
"pers": "string",
"custNr": "string",
"fnam": "string",
"snam": "string",
"sysId": "string"
},
"values": [{
"name": "name", // <-- attribute name 1
"value": "Langer Name",
"bodyRefId": "5d" // <-- body id 1
},
{
"name": "kurzname", // <-- attribute name 2
"value": "no_desc",
"bodyRefId": "42" // <-- body id 2
},
{
"name": "eindeutig", // <-- attribute name 3
"value": false,
"bodyRefId": "9d" // <-- body id 3
}
]
},
{ // row 2 from res1
"cell": "glossar", // <-- cell type
"id": "5c", // <- UUID v4 (generated by the function)
"cmv": null,
"crd": null,
"caption": {
"pers": "string",
"custNr": "string",
"fnam": "string",
"snam": "string",
"sysId": "string"
},
"values": [{
"name": "name", // <-- attribute name 1
"value": "Kein Name",
"bodyRefId": "5d" // <-- body id 1
},
{
"name": "kurzname", // <-- attribute name 2
"value": "short_desc",
"bodyRefId": "42" // <-- body id 2
},
{
"name": "eindeutig", // <-- attribute name 3
"value": true,
"bodyRefId": "9d" // <-- body id 3
}
]
},
{ // row 3 from res1
"cell": "glossar", // <-- cell type
"id": "5d", // <- UUID v4 (generated by the function)
"cmv": null,
"crd": null,
"caption": {
"pers": "string",
"custNr": "string",
"fnam": "string",
"snam": "string",
"sysId": "string"
},
"values": [{
"name": "name", // <-- attribute name 1
"value": "Kurzer Name",
"bodyRefId": "5d" // <-- body id 1
},
{
"name": "kurzname", // <-- attribute name 2
"value": "short_desc",
"bodyRefId": "42" // <-- body id 2
},
{
"name": "eindeutig", // <-- attribute name 3
"value": true,
"bodyRefId": "9d" // <-- body id 3
}
]
}
]
}
}
Blockquote
the returned array should be converted to match the metadata.
Each entry in the array describes an object in the result object.
and should be able to change implement the requirement in the function below.
function add(input1) {
let exampleValues1 = input1.metaData.cellMetaDataList[0].logicalData.body.map(({
exampleValues
}) => exampleValues);
return comb(exampleValues1,20);
}
the combination function .
function comb(args,output) {
var combination = [], max = args.length-1;
function helper(arr, i) {
for (var j=0, l=args[i].length; j<l; j++) {
var a = arr.slice(0); // clone arr
a.push(args[i][j]);
if (i==max)
combination.push(a);
else
helper(a, i+1);
}
}
helper([], 0);
while(combination.length < output){
combination = combination.concat(combination)}
return combination.sort(function() {
return .5 - Math.random();
}).slice(0,output); }
console.log(add(generatedObj1));
Sample result:
[["Langer Name", "no_desc", false],
["Kein Name", "short_desc", true]
["Kurzer Name", "short_desc", true]
];
the returned array should be converted to match the metadata.
Each entry in the array describes an object in the result object.
You can still just call the add function and get your input with it
The input does not change at all we are just changing the output... (that's why the ticket is named adaptation of the output structure)
For every string artay within the output of the comb function the add function should create one object within the cellData element. It should have cell type, an id, a null cmv and crd value, as well es the caption object
Most importantly it should have an values array having an object withe the name of the attribute (from body.name) the value (from the array comb returned) and a bodyRefId (from body.id)
How can I implement this in my function add()?
You can create an object from an array by filling the fields of the object using the Square brackets notation. The method would look like this:
function mapArrayToObject(cellDataValues) {
const obj = {};
cellDataValues.forEach(element => {
const fieldName = element[0];
const fieldValue = element[2];
obj[fieldName] = fieldValue;
});
return obj;
}
Update 09/17/2020 (The question was misunderstood)
After studying your question carefully I guess that your objective is the next one: After the execution of the add function what you want to get is an object with some fields (id, cell, caption...) and a values field that contains the values computed by the comb function, but parsed into objects that contains information about the body.
In order to achieve it I purpose a solution divided in 3 steps inside the add function:
Create an object with all the fields that are not related to the values computed by the comb function.
Execute the comb function.
Iterate through the values obtained, using the object created at step one as a template (cloning it) and use the index of the value you are iterating through to know which body you are pointing to in order to obtain the name and bodyRefId for each value.
The implementation would be:
function add(input1) {
// FIRST STEP: Creating the template object
const metaData = input1.metaData.cellMetaDataList[0];
const bodies = metaData.logicalData.body;
let emptyObj = {
id: "ID GENERATED BY THE FUNCTION",
cell: metaData.cell,
cmv: null,
crd: null,
caption: {
"pers": "string",
"custNr": "string",
"fnam": "string",
"snam": "string",
"sysId": "string"
}
};
// SECOND STEP: Calling to the comb function
let exampleValues1 = bodies.map(({ exampleValues }) => exampleValues);
const valuesArr = comb(exampleValues1,20);
// THIRD STEP: Parsing (Tricky part)
// Iterating through each collection of values -> [], [], []
const valuesObj = valuesArr.map(arr => {
// Cloning the template object
const obj = { ...emptyObj };
// Iterating through each value -> 'val1', 'val2', 'val3'
const valuesArr = arr.map((value, index) => {
// Using the index in order to know the body.
// For example, when index is 0 we know that we can get the name from bodies[0]
return {
name: bodies[index].name,
value: value,
bodyRefId: bodies[index].id
}
})
// Assigning the parsed values to the cloned template object
obj.values = valuesArr;
// Returning the object as we are using the map function
return obj;
});
// Now, valuesObj should have the expected structure
return valuesObj;
}
I am new to java script and ajax. I have a JSON and I want to remove outputs cell in this JSON:
{
"cells": [{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "print(\"hi\")",
"execution_count": 1,
"outputs": [{
"output_type": "stream",
"text": "hi\n",
"name": "stdout"
}]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "Python [Root]",
"display_name": "Python [Root]",
"language": "python"
},
"anaconda-cloud": {},
"language_info": {
"pygments_lexer": "ipython3",
"version": "3.5.0",
"codemirror_mode": {
"version": 3,
"name": "ipython"
},
"mimetype": "text/x-python",
"file_extension": ".py",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Untitled5.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
and this is my attempt on removing the outputs cell. This piece of code posts the data to above mentioned JSON:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';
// Create/edit the Gist
$.ajax({
url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
type: method,
dataType: 'json',
data: JSON.stringify(data_dup),
beforeSend: add_auth_token,
success: gist_success,
error: gist_error,
complete: complete_callback
});
};
But this code doesnt work. Can some one please guide how can we directly strip a key(outputs in this case) from ajax call and post it to JSON.
This is a gist extension of jupyter notebook and I am trying to strip output while posting it to gist on github
function _objectWithoutProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }
If you use ES6, you can use this syntax to remove outputs:
{
...data,
cells: data.cells.map(({ outputs, ...otherProps }) => otherProps),
}
Note: data is your complete object.
Given the below json structure:
{
"nodes": [
{
"type": "school",
"country": "US",
"name": "saint peter's",
"id": 1006
},
{
"type": "univeristy",
"country": "Brazil",
"name": "saint joseph's",
"id": 1007
}
...
],
"links": [
{
"source": 1006,
"target": 1007,
"value": 20
},
],
"types": [
{
"type": "school",
"image": "image01"
},
{
"type": "univeristy",
"image": "image02"
},
{
"type": "company",
"image": "image03"
},
]
}
I get the list of the type of nodes from types.type and append it to a html tag; assigning a color to each list item. When I change the color in the color picker container, in any of the list items, it only changes the color for .school , because it is hardcoded in here MyNode = d3.select("#node").selectAll(".school").select("circle");
how can I change it to match the type in the list item with the node type found in the nodes.type?
$(document).ready(function () {
$.getJSON("data.json", function (obj) {
$('#filterColor').data('types', obj.types.map(function (o) {
// console.log(o.type);
return o.type;
})).append(obj.types.map(function (o) {
return '<li>' + o.type + '<input class="color-picker" type="text"/></li>';
}).join(''));
$("#filterColor .color-picker").each(function(){
$(this).spectrum({
color: (function (m, s, c) {
return (c ? arguments.callee(m, s, c - 1) : '#') +
s[m.floor(m.random() * s.length)]
})(Math, '0123456789ABCDEF', 5),
preferredFormat: "rgb",
showInput: true,
showPalette: true,
showAlpha: true,
palette: [["red", "rgba(0, 255, 0, .5)", "rgb(0, 0, 255)"]],
change: function(color) {
MyNode = d3.select("#node").selectAll(".school").select("circle");
MyNode.style("fill", function(d) { return d3.rgb(color.toHexString()) });
ColorSchool = d3.rgb(color.toHexString());
}
});
});
});
});
which passes into this function:
function ColorType(d)
{
if (d.type == "school") { return ColorSchool;}
if (d.type == "univeristy"){ return Coloruniveristy;}
if (d.type == "company"){ return Colorcompany;}
}
You could store the type reference in the actual element, in a custom attribute. Since it's only one string you need, this might be enough to fix your problem.
When creating the <li> element, you add an attribute, e.g.: data-fortype, with the o.type string.
In the each that initializes the spectrum thingy, you extract it using this.getAttribute or the jQuery equivalent.
An example, in vanilla js: (I don't really know the jQuery API, sorry about that)
var data = {
"types": [{
"type": "school",
"image": "image01"
}, {
"type": "univeristy",
"image": "image02"
}, {
"type": "company",
"image": "image03"
}]
};
// Make UI from code:
makeUI();
function makeLi(type) {
return "<li>" +
type.type +
// (1) Here, the selector is stored in attr.
"<input class='test' data-forType='" +
type.type +
"' type='text' /></li>"
};
function onChange(e) {
// (2) Here, we retreive the attribute
console.log("Selector: " + e.target.getAttribute("data-forType"));
};
function makeUI() {
data.types.forEach(function(type) {
document.querySelector("ul").innerHTML += makeLi(type);
});
Array.from(document.querySelectorAll("li"))
.forEach(function(el) {
el.addEventListener("change", onChange);
});
};
<ul>
</ul>
how can i disable file nodes so that the tree only displays folders and not files, this is my code currently,
$(document).ready(function () {
//$("#MySplitter").splitter();
setupSplitter();
$("#divJsTreeDemo").bind("select_node.jstree", function (e, data) {
// if (document.location.href != data.rslt.obj.children("a").attr("href")) {
// document.location.href = data.rslt.obj.children("a").attr("href");
//
var id = data.rslt.obj.attr("id").replace("node", "");
// var tree = jQuery.jstree._reference("#divJsTreeDemo");
// var currentNode = tree._get_node(null, false);
// tree.refresh(currentNode);
GetChildObjects(id);
}).delegate("a", "click", function (e) {
//$("#divJsTreeDemo").jstree("toggle_node", this);
}).jstree({
"themes": {
"theme": "default",
"dots": false,
"icons": false
},
"plugins": [
"core", "themes", "json_data", "types", "ui"
],
"types": {
// I set both options to -2, as I do not need depth and children count checking
// Those two checks may slow jstree a lot, so use only when needed
"max_depth": -2,
"max_children": -2,
// I want only `drive` nodes to be root nodes
// This will prevent moving or creating any other type as a root node
"valid_children": ["drive"],
"types": {
// The default type
"default": {
// I want this type to have no children (so only leaf nodes)
// In my case - those are files
"valid_children": "none",
// If we specify an icon for the default type it WILL OVERRIDE the theme icons
"icon": {
"image": "../../Repository/Images/file.png"
}
},
// The `folder` type
"folder": {
// can have files and other folders inside of it, but NOT `drive` nodes
"valid_children": ["default", "folder"],
"icon": {
"image": "../../Repository/Images/folder.png"
}
}
}
},
"json_data": {
"ajax": {
"type": "POST",
"url": "GetTreeNodes",
"data": function (n) {
return { id: n.attr ? n.attr("id").replace("node", "") : 0 };
},
"async": true,
"success": function (data) {
RenderFileFolder(data);
}
}
}
});
});
I'm building the JSON object using JavaScript. How would I inset the following data to the bottom of the stack:
"hello": { "label":"Hello", "url":"#hello" }
in to the following variable:
var ListData = {
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
}
};
So the variable looks like:
var ListData = {
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
},
"hello": {
"label":"Hello",
"url":"#hello"
}
};
I used the following code but it doesn't seem to work:
var NewData = '"hello": { "label":"Hello", "url":"#hello" }';
ListData.push(NewData);
You can insert it directly with an object literal:
ListData.hello = { label: "Hello", url: "#hello" };
If you are using jQuery, you can use the .extend() jQuery API like:
$.extend(ListData, {"hello": { "label":"Hello", "url":"#hello" }});
I have one more solution using underscore.js module,
var _ = require("underscore");
var src = {
"main": {
"label": "Main",
"url": "#main"
},
"project": {
"label": "Project",
"url": "#project"
},
"settings": {
"label": "Settings",
"url": "#settings",
"subnav": [
{
"label": "Privacy",
"url": "#privacy"
},
{
"label": "Security",
"url": "#security"
},
{
"label": "Advanced",
"url": "#advanced"
}
]
}
};
var dest = {"hello": { "label":"Hello", "url":"#hello" }};
var data = _.extend(src, dest);
console.log(JSON.stringify(data));
Required op :
{"main":{"label":"Main","url":"#main"},"project":{"label":"Project","url":"#project"},"settings":{"label":"Settings","url":"#settings","subnav":[{"label":"Privacy","url":"#privacy"},{"label":"Security","url":"#security"},{"label":"Advanced","url":"#advanced"}]},"hello":{"label":"Hello","url":"#hello"}}
Keeping with you object literal statements just add another object to your ListData object.
ListData.hello = { "label":"Hello", "url":"#hello" };
push is only for Javascript Arrays.
A JavaScript Object Literal is a comma-separated list of name/value pairs wrapped by a pair of curly braces.
To append the property name of encampment name with a value of Valley Forge to the bottom of the stack, simply add the property name after the JSON object with a dot syntax. Then specify the value. (See 'Append data' below)
You can also delete the appended name/value pair from the object literal. (See 'Delete data below')
// Start with some JSON
var myJson = { "name":"George Washington", "rank":"General", "serial":"102" };
// Append data
myJson.encampment = "Valley Forge";
// Delete data
delete myJson.encampment