Add a param to a function that contains a default param - javascript

I have a code as following :
{
headerName: "A",
valueGetter: 'data.a',
field: 'a',
cellRenderer:ACellRenderer,
width: 100,
filter: 'number'
}
And this :
function ACellRenderer(params){
if(params.data && params.data.a){
// Do something
}
}
I don't understand where that params parameter came from, as I only call the ACellRenderer without any params.
I also want to call ACellRenderer with a param I pass to it, apparently doing this : cellRenderer:ACellRenderer(myParam) won't work.

I'm having a hard time understanding your question from the way it's worded, but perhaps you're looking to do this?
{
headerName: "A",
valueGetter: 'data.a',
field: 'a',
cellRenderer:function(){ACellRenderer(<put your parameter here>);},
width: 100,
filter: 'number'
}
Also, for future reference, the common term is argument, not param. Not that it matters that much, but it'll help you be understood better by other Javascript programmers.

This :
var Obj = {
headerName: "A",
valueGetter: 'data.a',
field: 'a',
cellRenderer:ACellRenderer,
width: 100,
filter: 'number'
}
Is just a definition of an object.
This line : cellRenderer:ACellRenderer Stores the function in that particular variable Basic JS like this :
var func = function(){}
Now calling it will be like :
Obj['cellRenderer']();
OR
Obj.cellRenderer();
The function expects an object as a parameter, i don't see how that is confusing.

Related

VueJs proper way to keep template clean without sacrificing performance

Our team is facing a problem with too much logics in template file which causes colleagues hard to debug.
I am thinking a proper way to increase the readability of the template file without losing performance.
Our team often include inline bitwise logic for dynamic class, style, etc. to fulfill the business logic under component template.
[Inline bitwise example]
<template> <!--Inline bitwise way-->
<div class="listContainer">
<div :class="`listItem ${_item.type == '1' ? 'itemTypeOne' : ''} ${_item.type == '2' ? 'itemTypeTwo' : ''}`" v-for="_item in list" :key="_item.key">
<div class="itemBg" :style="{top: _item.type == '1' ? '10px' : '20px'}"></div>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
list: [{key: "1", type: "1", value: "Value 1"}, { key: "2", type: "2", value: "Value 2"}],
};
},
methods: {},
computed: {},
}
</script>
To reduce these kind of logic code, I thought of using computed approach but I think it would cause computation overhead (Just in my opinion, feel free to correct me if I was wrong:)). It is because we cannot avoid using parameters with computed which lose the advantage of cache handled by vue itself. By using computed property with parameter approach, the parametrize anonymous function inside computed is keep being called which would potentially cause lower performance.
[Parametrized computed example]
<template>
<div class="listContainer">
<div :class="`listItem ${getItemClass(_item.type)}`" v-for="_item in list" :key="_item.key">
<div class="itemBg" :style="getItemBgStyle(_item.type)"></div>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
list: [{key: "1", type: "1", value: "Value 1"}, { key: "2", type: "2", value: "Value 2"}],
};
},
methods: {},
computed: {
getItemClass: function(){
return function($itemType){
console.log("getItemClass called"); /* Keep being called even _item.key didnt changed */
if($itemType == '1'){
return 'itemTypeOne'
}
if($itemType == '2'){
return 'itemTypeTwo'
}
}
},
getItemBgStyle: function(){
return function($itemType){
console.log("getItemClass called"); /* Same as getItemClass */
return {
top: $itemType == '1' ? '10px' : '20px'
}
}
}
},
}
</script>
Same with parametrized computed approach, parametrized method approach also cause this drawback. To keep this question in short, I'm not showing method approach here since it basically same with the computed approach. Here is the reference post that I studied: Can I pass parameters in computed properties in Vue.Js
My question is, is there a proper way to meet my aim (to keep template shorts without losing performance)?
Additionally, could anyone share with us the performance comparison between [Inline bitwise approach] vs [Parametrized computed approach] vs [Parametrized method approach].

Finding results that are part of a set with FlexSearch

I have an app that uses FlexSearch. In this app, I have an array of items that looks like this:
let results = [
{ id:'a', name:'The title', status:'in-stock' },
{ id:'b', name:'Another title', status:'out-of-stock' },
{ id:'c', name:'Some other', status:'discontinued' },
];
const resultSchema = {
id: 'id',
field: [
'name',
'status'
]
};
const resultIndex = new FlexSearch({
profile:'score',
doc: resultSchema
});
resultIndex.add(results);
My page has checkboxes for the statuses (in-stock, out-of-stock, and discontinued). My question is, how do I find results that are either a) in-stock or b) out-of-stock. I do not see a way to perform logical ORs with the where function. For example, I'd like to be able to say, give me all results that are either in-stock or out-of-stock. From a logical perspective, one could say, give me everything that is NOT discontinued. However, this is not my entire data set. For that reason, I'm trying to figure out how to do ORs within Flexsearch.
Thank you!
See the section Logical Operators in the readme. This seems to work:
const res = resultIndex.search([
{ field: 'status', query: 'in-stock', bool: 'or' },
{ field: 'status', query: 'out-of-stock', bool: 'or' },
]);
Strangely, { field: 'status', query: 'discontinued', bool: 'not' } didn't work when I tried it.
Doesn't using a custom function solve your problem?(found it in the document)
Something like this:
resultIndex.where(function(item){
return item.status === "in-stock" || item.status === "out-of-stock";
});

How to use custom global functions inside field value expressions in Cx?

I have a somewhat complex case where I need to apply custom formatting to a JavaScript expression that calculates the value of a field inside a Grid.
<Grid records:bind="$page.data"
columns={[
{
field: 'seatbeltViolations',
header: 'Seatbelt Violations',
format:'n;0',
aggregate: 'sum',
aggregateField: 'seatbelts',
align: 'right'
},{
field: "distance",
header: "Distance",
format: "n;0",
aggregate: "sum",
aggregateField: "distance",
align: "right"
},{
field: 'seatbeltViolationsPer100Km',
header: 'Seatbelts per 100km',
format: 'n;1',
footer: {
expr: '0.1 * Math.round(10.0 * {$group.seatbelts}/{$group.distance})'
},
align: 'right'
}]} />
Is there a way to use custom global functions, that perform the given operation, within the expression? Something like this:
// this does not work
expr: 'Format.value({$group.seatbelts}/{$group.distance}, "n;1")'
I hope my question was clear enough :)
I think the easiest way would be to use computable here instead of an expression. Something along the lines of:
...
footer: computable("$group.seatbelts", "$group.distance", (p, q) =>
{
return q != 0 ? Format.value(100.0 * p / q, "n;1") : '--';
}),
...
This way you can have footers as complex as you like, and you can easily abstract the logic away into a generic factory function returning anything you want. For an example of this, take a look at this fiddle:
https://cxjs.io/fiddle/?f=xWw8ob40
There's also an undocumented feature of using expressions within string templates:
footer: {
tpl: '{[{$group.seatbelts} != 0 ? {$group.distance}/{$group.seatbelts} : null]:n;1}'
}

Create object from Backbone collection that maps model values to one another

We are using Backgrid which allows you to define grid columns with an array of Javascript objects which it converts to a collection. We are trying to take advantage of this to have configurable validation on a column by column basis, so we might have the following where we've added a "validator" function to a couple of the columns:
[
{
label: "Delete",
name: "delete",
cell: "boolean"
},
{
label: "Alias",
name: "alias",
cell: "string",
sortType: "toggle",
validator: function (value) {
return true;
}
},
{
label: "Assigned Server",
name: "assignedServer",
cell: "string",
sortType: "toggle",
validator: function (value) {
return new Error("Cannot Assign Server")
}
}
]
We are listening to edits to the grid in the following prescribed manner and for the purposes of this question we can ignore the model argument to the function but concentrate on the column (delete, alias or assignedServer from above) which is itself a model in a collection. So far I have a snippet of code leveraging underscore.js's _.filter that returns the validatableColumns but I want to take this further and end up with an object of the format {name: validator, etc...}. Bearing in mind my specific use case, what is a succinct way to create an object from a Backbone collection that maps model values to one another?
certificateGrid.listenTo(certificateCollection, "backgrid:edited", function (model, column) {
var validatableColumns = _.filter(column.collection.models, function (c) {
return c.get('validator');
});
//etc.
Using _.reduce seems to do the trick:
var validatorFns = _.reduce(column.collection.models, function (fns, model) {
var validator = model.get('validator');
if (model.get('validator')) {
fns[model.get('name')] = validator;
}
return fns;
}, {});

jqxListBox:Check listbox item based on value member

Hi I have the following code
var source =
{
datatype: "json",
datafields: [
{ name: 'Name' },
{ name: 'ID'},
],
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#polistbox").jqxListBox({ source: dataAdapter, displayMember: "Name", valueMember: "ID", checkboxes: true, width: '255px', height: '100px'});
I want to check one item using the value member.
ie) I want to check the item having value 2.How can i achieve this?
I found the following solution http://jsfiddle.net/jqwidgets/vv3gK/ .
But how can i achieve this in my code?
Did you mean check by index or value? Here's an example.
You could always use checkIndex like so:
$("#polistbox").jqxListBox('checkIndex',2);
In the link that you gave me - It showed you everything you need, unless you haven't told us something else.
I know it's old but maybe someone will use it.
This works for me.
var ID = id you want;
var jqItem = $("#polistbox").jqxListBox('getItemByValue', ID);
$("#polistbox").jqxListBox('selectItem', jqItem );

Categories