It is corret usage to create a tab for mithril? - mithril.js

I want to create a simple Tab but I think it is strange for my using:
var root = document.body
var index = {
view: () => index.html,
html: m('div', { id: 'div1' }, [
[
(function () {
let value = ["A", "B", "C", "D"]
let output = []
for (let i = 0; i < 4; i++) {
output.push(m('input', {
class: (function () {
if (i == 0) return "onit"
})(),
type: 'button',
value: value[i],
onclick: function () {
let div1 = document.getElementById("div1")
let btn = div1.getElementsByTagName("input")
let div1_div = div1.getElementsByTagName("div")
let _this = this
let num = (function () {
for (let i = 0; i < btn.length; i++) {
if (btn[i] == _this) {
return i
}
}
})()
for (let i = 0; i < btn.length; i++) {
btn[i].className = ""
}
this.className = "onit"
for (let i = 0; i < div1_div.length; i++) {
div1_div[i].setAttribute("style", "dispaly:none")
}
div1_div[num].setAttribute("style", "display:block")
}
}))
}
return output
})()
],
[
(function () {
let arr = ["aaa", "bbb", "ccc", "ddd"]
let output = []
for (let i = 0; i < 4; i++) {
output.push(m("div", { style: (the => i == 0 ? "display:block" : undefined)() }, arr[i]))
}
return output
})()
]
])
}
m.route(root, "/index", {
"/index": index
})
Is there any other simple way to achieve this?
If I click the button, the style of button will change and the display of all "div" will be changed. Screenshot

In mithril.js views you can only use expressions, for-loops, ifs and so on are no expressions and only possible the way you did it. Nevertheless there are other ways to achieve this
Loops can be achieved using the functional counterparts
let values = ["A", "B", "C", "D"]
let output = []
function(){
for (let i = 0; i < 4; i++) {
output.push(m('span', value)
}
return output
}()
can be written as
values.map(value => m('span', value)
if-Statements can be written using the ternary expression
function() {
if (condition) {
return 'this'
} else {
return 'that'
}
}()
just use
condition ? 'this' : 'that'
You can also use view functions if your view code gets to deeply nested and you need custom logic:
function someOtherView(someData) {
if (someData.shouldBeShown) {
return someData.text
}
}
function someView() {
...
someOtherView(someData)
...
}
This also makes your views more readable.

Related

Row Span AutoGrouping and Bug

I've created a plnkr to auto-group row-spans the way you would really expect it to work out of the box IMHO.
Anyhow... doing this surfaces an apparent bug... the rowSpan is not consistently applied to the grid.. if you scroll up and down, it sometimes applies, and sometimes does not.
In the screenshot below... you can see 'Aaron Peirsol' is spanning... but if I scroll up and down it might not span on him... not consistent.
Here 'Aaron Peirsol' is no longer spanning all 3 rows -- all I did was scroll up and back down
See this Sample
https://plnkr.co/edit/UxOcCL1SEY4tScn2?open=app%2Fapp.component.ts
Here I've added columndefs for the grouping
{
field: 'athlete',
rowSpan: params => params.data.groupCount,
cellClassRules: {
'cell-span': "data.isFirst && data.groupCount>1",
},
width: 200,
},
{field:'groupCount', width: 20}, /* included for debugging */
{field:'isFirst', width: 20}, /* included for debugging */
And here I'm doing the auto-grouping code:
onGridReady(params: GridReadyEvent) {
this.http
.get<any[]>('https://www.ag-grid.com/example-assets/olympic-winners.json')
.subscribe((data) => {
let groupKey = 'athlete';
let sorted = data.sort((a,b) => (a[groupKey] > b[groupKey]) ? 1 :
((b[groupKey] > a[groupKey]) ? -1 : 0));
let filtered = sorted.filter(x => {
return x[groupKey] < 'Albert' && x[groupKey];
});
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
let keyValue = x[key];
if (rv[keyValue] === undefined)
{
rv[keyValue] = 0;
}
if (keyValue) {
rv[keyValue] ++;
}
return rv;
}, {});
};
let grouped = groupBy(filtered, groupKey);
let prev = '';
for (let i=0; i<filtered.length; i++)
{
let keyValue = filtered[i][groupKey];
filtered[i]['groupCount'] = grouped[keyValue];
if (keyValue == prev)
{
filtered[i]['isFirst'] = false;
}
else
{
filtered[i]['isFirst'] = true;
}
prev = keyValue;
}
this.rowData = filtered});
}
OK, found the issue...
rowSpan function must only return a span count for the first row of the span...
every other row it must return 1
I've updated the plunker
public columnDefs: ColDef[] = [
{
field: 'athlete',
rowSpan: params => params.data.groupRowCount == 1 ? params.data.groupCount: 1, //THIS IS CRUCIAL.. only return count for first row
cellClassRules: {
'cell-span': "data.groupRowCount==1 && data.groupCount>1",
},
width: 200,
},

Expand Text of Compact Data

I am stuck with some data manipulation.
This is a small portion of the input data (df):
site=c("C000-C002","C420-C421,C424")
histology=c("9835-9836","9811-9812,9837")
category=c("Leukemia","Leukemia")
df=data.frame(site,histology,category)
And this is what I want the processed data to look like:
You may assume Site and Histology are both 4-digit after text splitting.
In case anyone is interested, the full data table is here
Please help with the text processing, or if anyone knows an existing processed package or database in a similar format as the image, that would be great too.
Thank you very much.
I don't know R language. So I tried with Javascript as following.
function mapStartEnd(start, end) {
let list = [];
let info = {};
const siteStart = start.match(/([A-Z])(\d{3})/);
if (siteStart) {
const siteEnd = end.match(/([A-Z])(\d{3})/);
info = {
type: "site",
prefix: siteStart[1],
numLength: 3,
from: parseInt(siteStart[2], 10),
to: parseInt(siteEnd[2], 10),
};
}
const histologyStart = start.match(/\d{4}/);
if (histologyStart) {
const histologyEnd = end.match(/\d{4}/);
info = {
type: "histology",
prefix: "",
numLength: 4,
from: parseInt(histologyStart[0], 10),
to: parseInt(histologyEnd[0], 10),
};
}
const categoryStart = start.match(/[A-Z][a-z]+/);
if (categoryStart) {
const categoryEnd = end.match(/[A-Z][a-z]+/);
info = {
type: "category",
prefix: "",
numLength: 0,
from: categoryStart[0],
to: categoryEnd[0],
};
}
if (!info.numLength) {
list = [info.from, info.to];
} else {
for (let i = info.from; i <= info.to; i++) {
list.push(info.prefix + i.toString().padStart(info.numLength, "0"));
}
}
return list;
}
function c(list) {
return list.map((list2) => {
return list2.split(",").reduce((prev, cur) => {
const [start, end] = cur.split("-");
if (!end) prev.push(start);
else prev = [...prev, ...mapStartEnd(start, end)];
return prev;
}, []);
});
}
function map3(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
for (let j = 0; j < histologys.length; j++) {
const histology = histologys[j];
for (let k = 0; k < categorys.length; k++) {
const category = categorys[k];
// JSON format
// list.push({ site, histology, category });
// CSV format
list.push(`${site},${histology},${category}`);
}
}
}
return list;
}
function frame(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
const histology = histologys[i];
const category = categorys[i];
list = [...list, ...map3(site, histology, category)];
}
return list;
}
const site = c(["C000-C002", "C420-C421,C424"]);
const histology = c(["9835-9836", "9811-9812,9837"]);
const category = c(["Leukemia", "Leukemia"]);
const df = frame(site, histology, category);
console.log(df);
Result:
[
"C000,9835,Leukemia",
"C000,9836,Leukemia",
"C001,9835,Leukemia",
"C001,9836,Leukemia",
"C002,9835,Leukemia",
"C002,9836,Leukemia",
"C420,9811,Leukemia",
"C420,9812,Leukemia",
"C420,9837,Leukemia",
"C421,9811,Leukemia",
"C421,9812,Leukemia",
"C421,9837,Leukemia",
"C424,9811,Leukemia",
"C424,9812,Leukemia",
"C424,9837,Leukemia"
]
https://jsfiddle.net/dnu2g0vr/

Vue.js list not updating when data changes

i'm trying re-organised a list of data. I have given each li a unique key, but still, no luck!
I have had this working before exactly like below, think i'm cracking up!
let app = new Vue({
el: '#app',
data: {
list: [
{ value: 'item 1', id: '43234r' },
{ value: 'item 2', id: '32rsdf' },
{ value: 'item 3', id: 'fdsfsdf' },
{ value: 'item 4', id: 'sdfg543' }
]
},
methods: {
randomise: function() {
let input = this.list;
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
this.list = input;
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="item in list" :key="item.id">{{ item.value }}</li>
</ul>
Randomize
</div>
Edit:
Thanks for the answers, to be honest the example I provided may not have been the best for my actual issue I was trying to solve. I think I may have found the cause of my issue.
I'm basically using a similar logic as above, except i'm moving an array of objects around based on drag and drop, this works fine with normal HTML.
However, i'm using my drag and drop component somewhere else, which contains ANOTHER component and this is where things seem to fall apart...
Would having a component within another component stop Vue from re-rendering when an item is moved within it's data?
Below is my DraggableBase component, which I extend from:
<script>
export default {
data: function() {
return {
dragStartClass: 'drag-start',
dragEnterClass: 'drag-enter',
activeIndex: null
}
},
methods: {
setClass: function(dragStatus) {
switch (dragStatus) {
case 0:
return null;
case 1:
return this.dragStartClass;
case 2:
return this.dragEnterClass;
case 3:
return this.dragStartClass + ' ' + this.dragEnterClass;
}
},
onDragStart: function(event, index) {
event.stopPropagation();
this.activeIndex = index;
this.data.data[index].dragCurrent = true;
this.data.data[index].dragStatus = 3;
},
onDragLeave: function(event, index) {
this.data.data[index].counter--;
if (this.data.data[index].counter !== 0) return;
if (this.data.data[index].dragStatus === 3) {
this.data.data[index].dragStatus = 1;
return;
}
this.data.data[index].dragStatus = 0;
},
onDragEnter: function(event, index) {
this.data.data[index].counter++;
if (this.data.data[index].dragCurrent) {
this.data.data[index].dragStatus = 3;
return;
}
this.data.data[index].dragStatus = 2;
},
onDragOver: function(event, index) {
if (event.preventDefault) {
event.preventDefault();
}
event.dataTransfer.dropEffect = 'move';
return false;
},
onDragEnd: function(event, index) {
this.data.data[index].dragStatus = 0;
this.data.data[index].dragCurrent = false;
},
onDrop: function(event, index) {
if (event.stopPropagation) {
event.stopPropagation();
}
if (this.activeIndex !== index) {
this.data.data = this.array_move(this.data.data, this.activeIndex, index);
}
for (let index in this.data.data) {
if (!this.data.data.hasOwnProperty(index)) continue;
this.data.data[index].dragStatus = 0;
this.data.data[index].counter = 0;
this.data.data[index].dragCurrent = false;
}
return false;
},
array_move: function(arr, old_index, new_index) {
if (new_index >= arr.length) {
let k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr; // for testing
}
}
}
</script>
Edit 2
Figured it out! Using the loop index worked fine before, however this doesn't appear to be the case this time!
I changed the v-bind:key to use the database ID and this solved the issue!
There are some Caveats with arrays
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
To overcome caveat 1, both of the following will accomplish the same as vm.items[indexOfItem] = newValue, but will also trigger state updates in the reactivity system:
Vue.set(vm.items, indexOfItem, newValue)
Or in your case
randomise: function() {
let input = this.list;
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = input[randomIndex];
Vue.set(input, randomIndex, input[i]);
Vue.set(input, i, itemAtIndex);
}
this.list = input;
}
Here is an working example: Randomize items fiddle
Basically I changed the logic of your randomize function to this:
randomize() {
let new_list = []
const old_list = [...this.list] //we don't need to copy, but just to be sure for any future update
while (new_list.length < 4) {
const new_item = old_list[this.get_random_number()]
const exists = new_list.findIndex(item => item.id === new_item.id)
if (!~exists) { //if the new item does not exists in the new randomize list add it
new_list.push(new_item)
}
}
this.list = new_list //update the old list with the new one
},
get_random_number() { //returns a random number from 0 to 3
return Math.floor(Math.random() * 4)
}
randomise: function() { let input = this.list;
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = this.list[randomIndex];
Vue.set(this.list,randomIndex,this.list[i])
this.list[randomIndex] = this.list[i];
this.list[i] = itemAtIndex;
} this.list = input;
}
Array change detection is a bit tricky in Vue. Most of the in place
array methods are working as expected (i.e. doing a splice in your
$data.names array would work), but assigining values directly (i.e.
$data.names[0] = 'Joe') would not update the reactively rendered
components. Depending on how you process the server side results you
might need to think about these options described in the in vue
documentation: Array Change Detection.
Some ideas to explore:
using the v-bind:key="some_id" to have better using the push to add
new elements using Vue.set(example1.items, indexOfItem, newValue)
(also mentioned by Artokun)
Source
Note that it works but im busy so i cant optimize it, but its a little bit too complicted, i Edit it further tomorrow.
Since Vue.js has some caveats detecting array modification as other answers to this question highlight, you can just make a shallow copy of array before randomazing it:
randomise: function() {
// make shallow copy
let input = this.list.map(function(item) {
return item;
});
for (let i = input.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random()*(i+1));
let itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
this.list = input;
}

Reading from an object

I want to retrieve the values of marked dates how can I get all the marked dates where marked value is true from this object:
alert(JSON.stringify(this.state._markedDates))
{"2018-09-26":{"marked":true}, "2018-09-27":{"marked":false}, "2018-09-29":{"marked":true}}
Expected Result :
{"2018-09-26","2018-09-29"}
I tried the following but datelist is still empty:
for(var i=0; i<this.state._markedDates.length ; i++)
{
if(this.state._markedDates[i].marked == true)
{
this.state.datesList.push(_markedDates[i])
}
}
let dates = {
"2018-09-26":{"marked":true},
"2018-09-27":{"marked":false},
"2018-09-29":{"marked":true}
}
let markedDates=[];
Object.keys(dates).map(date => {
if(dates[date].marked){ markedDates.push(date)}
})
console.log(markedDates)
There are different ways of approaching this, you could filter them for example as below:
let dates = ["2018-09-26":{"marked":true}, "2018-09-27":{"marked":false}, "2018-09-29":{"marked":true}];
let filtered = dates.filter( date => {
if(date.marked === true) {
return date;
}
});
// filtered = {"2018-09-26":{"marked":true}, "2018-09-29":{"marked":true}};
This is how you can get all of the dates where marked = true.
Then you can do
let keyNames = Object.keys(filtered);
console.log(keyNames); // Outputs ["2018-09-26","2018-09-29"]
As a for loop
let markedDates = [];
for(var i=0; i<this.state._markedDates.length; i++)
{
if(this.state._markedDates[i].marked === true)
{
markedDates.push(_markedDates[i])
}
}
this.setState({ObjectIWantToSet: markedDates})
let dates = []
let obj = {"2018-09-26":{"marked":true}, "2018-09-27":{"marked":false}, "2018-09-29":{"marked":true}}
for(date in obj)
{
if(a[date]["marked"])
{
dates.push(date)
}
}
console.log(dates)

Update the data in amcharts in angular5

I am using xy chart in amcharts as per my requirement.
In that amcharts, whenever on click of a bubble, I need to highlight the bubbles. So I have added listeners to my options as follows:
"listeners": [
{
"event": "clickGraphItem",
"method": function(event) {
var bubbleId = event.item.dataContext.id;
var toolTip = "";
dataProvider.forEach((data) => {
if (bubbleId != "" && bubbleId == data.id) {
if (data.bubbleSize == 10) {
data.bubbleSize = 20;
data.shape = "diamond";
} else {
data.bubbleSize = 10;
data.shape = "round";
}
} else {
data.bubbleSize = 10;
data.shape = "round";
}
});
this.AmCharts.updateChart(this.chart, () => {
// Change whatever properties you want
this.chart.dataProvider = dataProvider;
});
}
}],
But I am getting an error as "Cannot read property 'Amcharts' of undefined". I am not able to resolve the issue. Can anyone help me on this?
Referal Code for Amcharts angular as follows:
https://github.com/amcharts/amcharts3-angular2