How to get key press work in St.Entry of gjs - gnome-shell

I want to press the 'Enter' key to call a function; I test many codes in key-press-event part, but no one work. I also don't know which key_symbol is the right one between those Clutter.KEY_Escape KEY_ISO_Enter KEY_KP_Enter KEY_3270_Enter.
other signal like 'primary-icon-clicked' works.
https://gjs-docs.gnome.org/clutter9~9_api/clutter.actor#signal-key-press-event almost say nothing.
let input = new St.Entry({
name: 'searchEntry',
style_class: 'big_text',
primary_icon: new St.Icon({ gicon: local_icon("countdown-symbolic.svg") }),
secondary_icon: new St.Icon({ gicon: local_icon("stopwatch-symbolic.svg") }),
can_focus: true,
hint_text: _('xxxx'),
track_hover: true,
x_expand: true,
});
input.connect('primary-icon-clicked', ()=>{add_timer();});
input.connect('secondary-icon-clicked', ()=>{add_timer();});
//~ input.connect('key-press-event', (event)=>{if(event.get_key_symbol() == Clutter.KEY_Left)add_timer();});
input.connect('key-press-event', (self, event)=>{
//~ let [success, keyval] = event.get_keyval();
//~ let keyname = Gdk.keyval_name(keyval);
//~ if (keyname === "Control_L"){add_timer();}
//~ const symbol = event.get_key_symbol();
//~ if (symbol === Clutter.KEY_KP_Enter) {add_timer(); return true;}
//~ if (event.get_key_symbol() === Clutter.KEY_Enter){add_timer();}
//~ if(event.keyval == Clutter.KEY_Enter){add_timer();} Clutter.KEY_Escape KEY_ISO_Enter KEY_KP_Enter KEY_3270_Enter KEY_equal
});
item_input.add(input);

If you want to run a callback when Enter is pressed in the entry, you probably want to connect to the activate signal of the child Clutter.Text actor:
let entry = new St.Entry();
entry.clutter_text.connect('activate', (actor) => {
log(`Activated: ${actor.text}`);
});
For filtering input, note that Clutter.InputContentPurpose and Clutter.InputContentHintFlags are just hints for the input method. In other words, this is like when a smartphone knows to show the phone dialer keyboard instead of the QWERTY keyboard.
If you want to ignore "invalid" keypresses, you'll just have to do it the hard way:
const allowedKeysyms = [
Clutter.KEY_KP_0,
...
Clutter.KEY_KP_9,
Clutter.KEY_0,
...
Clutter.KEY_9,
Clutter.KEY_colon,
];
entry.connect('key-press-event', (widget, event) => {
if (!allowedKeysms.includes(event.get_key_symbol()))
return Clutter.EVENT_STOP;
return Clutter.EVENT_PROPAGATE;
});

Related

How can I run useEffect on state change only and not on mount? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
ECMA 5+:
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // šŸ‘ˆ null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype
Note, though, that this creates an unnecessary array (the return value of keys).
Pre-ECMA 5:
function isEmpty(obj) {
for(var prop in obj) {
if(Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
jQuery:
jQuery.isEmptyObject({}); // true
lodash:
_.isEmpty({}); // true
Underscore:
_.isEmpty({}); // true
Hoek
Hoek.deepEqual({}, {}); // true
ExtJS
Ext.Object.isEmpty({}); // true
AngularJS (version 1)
angular.equals({}, {}); // true
Ramda
R.isEmpty({}); // true
If ECMAScript 5 support is available, you can use Object.keys():
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
For those of you who have the same problem but use jQuery, you can use jQuery.isEmptyObject.
Performance
Today 2020.01.17, I performed tests on macOS High Sierra 10.13.6 on Chrome v79.0, Safari v13.0.4, and Firefox v72.0; for the chosen solutions.
Conclusions
Solutions based on for-in (A, J, L, M) are fastest
Solutions based on JSON.stringify (B, K) are slow
Surprisingly, the solution based on Object (N) is also slow
NOTE: This table does not match the photo below.
Details
There are 15 solutions presented in the snippet below.
If you want to run a performance test on your machine, click HERE.
This link was updated 2021.07.08, but tests originally were performed here - and results in the table above came from there (but now it looks like that service no longer works).
var log = (s, f) => console.log(`${s} --> {}:${f({})} {k:2}:${f({ k: 2 })}`);
function A(obj) {
for (var i in obj) return false;
return true;
}
function B(obj) {
return JSON.stringify(obj) === "{}";
}
function C(obj) {
return Object.keys(obj).length === 0;
}
function D(obj) {
return Object.entries(obj).length === 0;
}
function E(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
function F(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
function G(obj) {
return typeof obj === "undefined" || !Boolean(Object.keys(obj)[0]);
}
function H(obj) {
return Object.entries(obj).length === 0 && obj.constructor === Object;
}
function I(obj) {
return Object.values(obj).every((val) => typeof val === "undefined");
}
function J(obj) {
for (const key in obj) {
if (hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
function K(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
function L(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) return false;
}
return true;
}
function M(obj) {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
return false;
}
}
return true;
}
function N(obj) {
return (
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
Object.getPrototypeOf(obj) === Object.prototype
);
}
function O(obj) {
return !(Object.getOwnPropertyNames !== undefined
? Object.getOwnPropertyNames(obj).length !== 0
: (function () {
for (var key in obj) break;
return key !== null && key !== undefined;
})());
}
log("A", A);
log("B", B);
log("C", C);
log("D", D);
log("E", E);
log("F", F);
log("G", G);
log("H", H);
log("I", I);
log("J", J);
log("K", K);
log("L", L);
log("M", M);
log("N", N);
log("O", O);
You can use Underscore.js.
_.isEmpty({}); // true
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
see http://bencollier.net/2011/04/javascript-is-an-object-empty/
How about using JSON.stringify? It is almost available in all modern browsers.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
There is a simple way if you are on a newer browser.
Object.keys(obj).length === 0
Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:
function isEmptyObject(obj) {
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}
Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.
Tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:
(for...in...) is the fastest option to use!
Object.keys(obj).length is 10 times slower for empty objects
JSON.stringify(obj).length is always the slowest (not suprising)
Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
See detailed testing results and test code at Is object empty?
My take:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
var a = {
a: 1,
b: 2
}
var b = {}
console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true
Just, I don't think all browsers implement Object.keys() currently.
I am using this.
function isObjectEmpty(object) {
var isEmpty = true;
for (keys in object) {
isEmpty = false;
break; // exiting since we found that the object is not empty
}
return isEmpty;
}
Eg:
var myObject = {}; // Object is empty
var isEmpty = isObjectEmpty(myObject); // will return true;
// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"};
// check if the object is empty
isEmpty = isObjectEmpty(myObject); // will return false;
from here
Update
OR
you can use the jQuery implementation of isEmptyObject
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
Just a workaround. Can your server generate some special property in case of no data?
For example:
var a = {empty:true};
Then you can easily check it in your AJAX callback code.
Another way to check it:
if (a.toSource() === "({})") // then 'a' is empty
EDIT:
If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.
1. Using Object.keys
Object.keys will return an Array, which contains the property names of the object. If the length of the array is 0, then we know that the object is empty.
function isEmpty(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
We can also check this using Object.values and Object.entries.
This is typically the easiest way to determine if an object is empty.
2. Looping over object properties with forā€¦in
The forā€¦in statement will loop through the enumerable property of object.
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
In the above code, we will loop through object properties and if an object has at least one property, then it will enter the loop and return false. If the object doesnā€™t have any properties then it will return true.
#3. Using JSON.stringify
If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
4. Using jQuery
jQuery.isEmptyObject(obj);
5. Using Underscore and Lodash
_.isEmpty(obj);
Resource
function isEmpty(obj) {
for(var i in obj) { return false; }
return true;
}
The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.
The script works on ES6.
const isEmpty = (obj) => {
if (obj === null ||
obj === undefined ||
Array.isArray(obj) ||
typeof obj !== 'object'
) {
return true;
}
return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty('')); // true
console.log(isEmpty(33)); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello')); // true
console.log(isEmpty([1, 2, 3])); // true
console.log(isEmpty({ test: 1 })); // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date())); // true
console.log(isEmpty(Infinity)); // true
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
The correct answer is:
function isEmptyObject(obj) {
return (
Object.getPrototypeOf(obj) === Object.prototype &&
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0
);
}
This checks that:
The object's prototype is exactly Object.prototype.
The object has no own properties (regardless of enumerability).
The object has no own property symbols.
In other words, the object is indistinguishable from one created with {}.
jQuery have special function isEmptyObject() for this case:
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
Read more on http://api.jquery.com/jQuery.isEmptyObject/
Caveat! Beware of JSON's limitiations.
javascript:
obj={ f:function(){} };
alert( "Beware!! obj is NOT empty!\n\nobj = { f:function(){} }" +
"\n\nJSON.stringify( obj )\n\nreturns\n\n" +
JSON.stringify( obj ) );
displays
Beware!! obj is NOT empty!
obj = { f:function(){} }
JSON.stringify( obj )
returns
{}
To really accept ONLY {}, the best way to do it in Javascript using Lodash is:
_.isEmpty(value) && _.isPlainObject(value)
In addition to Thevs answer:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
it's jquery + jquery.json
Sugar.JS provides extended objects for this purpose. The code is clean and simple:
Make an extended object:
a = Object.extended({})
Check it's size:
a.size()
Pure Vanilla Javascript, and full backward compatibility
function isObjectDefined (Obj) {
if (Obj === null || typeof Obj !== 'object' ||
Object.prototype.toString.call(Obj) === '[object Array]') {
return false
} else {
for (var prop in Obj) {
if (Obj.hasOwnProperty(prop)) {
return true
}
}
return JSON.stringify(Obj) !== JSON.stringify({})
}
}
console.log(isObjectDefined()) // false
console.log(isObjectDefined('')) // false
console.log(isObjectDefined(1)) // false
console.log(isObjectDefined('string')) // false
console.log(isObjectDefined(NaN)) // false
console.log(isObjectDefined(null)) // false
console.log(isObjectDefined({})) // false
console.log(isObjectDefined([])) // false
console.log(isObjectDefined({a: ''})) // true
IsEmpty Object, unexpectedly lost its meaning i.e.: it's programming semantics, when our famous guru from Yahoo introduced the customized non-enumerable Object properties to ECMA and they got accepted.
[ If you don't like history - feel free to skip right to the working code ]
I'm seeing lots of good answers \ solutions to this question \ problem.
However, grabbing the most recent extensions to ECMA Script is not the honest way to go. We used to hold back the Web back in the day to keep Netscape 4.x, and Netscape based pages work and projects alive, which (by the way) were extremely primitive backwards and idiosyncratic, refusing to use new W3C standards and propositions [ which were quite revolutionary for that time and coder friendly ] while now being brutal against our own legacy.
Killing Internet Explorer 11 is plain wrong! Yes, some old warriors that infiltrated Microsoft remaining dormant since the "Cold War" era, agreed to it - for all the wrong reasons. - But that doesn't make it right!
Making use, of a newly introduced method\property in your answers and handing it over as a discovery ("that was always there but we didn't notice it"), rather than a new invention (for what it really is), is somewhat 'green' and harmful. I used to make such mistakes some 20 years ago when I still couldn't tell what's already in there and treated everything I could find a reference for, as a common working solution...
Backward compatibility is important !
We just don't know it yet. That's the reason I got the need to share my 'centuries old' generic solution which remains backward and forward compatible to the unforeseen future.
There were lots of attacks on the in operator but I think the guys doing that have finally come to senses and really started to understand and appreciate a true Dynamic Type Language such as JavaScript and its beautiful nature.
My methods aim to be simple and nuclear and for reasons mentioned above, I don't call it "empty" because the meaning of that word is no longer accurate. Is Enumerable, seems to be the word with the exact meaning.
function isEnum( x ) { for( var p in x )return!0; return!1 };
Some use cases:
isEnum({1:0})
true
isEnum({})
false
isEnum(null)
false
Thanks for reading!
Best one-liner solution I could find (updated):
isEmpty = obj => !Object.values(obj).filter(e => typeof e !== 'undefined').length;
console.log(isEmpty({})) // true
console.log(isEmpty({a: undefined, b: undefined})) // true
console.log(isEmpty({a: undefined, b: void 1024, c: void 0})) // true
console.log(isEmpty({a: [undefined, undefined]})) // false
console.log(isEmpty({a: 1})) // false
console.log(isEmpty({a: ''})) // false
console.log(isEmpty({a: null, b: undefined})) // false
Another alternative is to use is.js (14kB) as opposed to jquery (32kB), lodash (50kB), or underscore (16.4kB). is.js proved to be the fastest library among aforementioned libraries that could be used to determine whether an object is empty.
http://jsperf.com/check-empty-object-using-libraries
Obviously all these libraries are not exactly the same so if you need to easily manipulate the DOM then jquery might still be a good choice or if you need more than just type checking then lodash or underscore might be good. As for is.js, here is the syntax:
var a = {};
is.empty(a); // true
is.empty({"hello": "world"}) // false
Like underscore's and lodash's _.isObject(), this is not exclusively for objects but also applies to arrays and strings.
Under the hood this library is using Object.getOwnPropertyNames which is similar to Object.keys but Object.getOwnPropertyNames is a more thorough since it will return enumerable and non-enumerable properties as described here.
is.empty = function(value) {
if(is.object(value)){
var num = Object.getOwnPropertyNames(value).length;
if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){
return true;
}
return false;
} else {
return value === '';
}
};
If you don't want to bring in a library (which is understandable) and you know that you are only checking objects (not arrays or strings) then the following function should suit your needs.
function isEmptyObject( obj ) {
return Object.getOwnPropertyNames(obj).length === 0;
}
This is only a bit faster than is.js though just because you aren't checking whether it is an object.
I know this doesn't answer 100% your question, but I have faced similar issues before and here's how I use to solve them:
I have an API that may return an empty object. Because I know what fields to expect from the API, I only check if any of the required fields are present or not.
For example:
API returns {} or {agentID: '1234' (required), address: '1234 lane' (opt),...}.
In my calling function, I'll only check
if(response.data && response.data.agentID) {
do something with my agentID
} else {
is empty response
}
This way I don't need to use those expensive methods to check if an object is empty. The object will be empty for my calling function if it doesn't have the agentID field.
We can check with vanilla js with handling null or undefined check also as follows,
function isEmptyObject(obj) {
return !!obj && Object.keys(obj).length === 0 && obj.constructor === Object;
}
//tests
isEmptyObject(new Boolean()); // false
isEmptyObject(new Array()); // false
isEmptyObject(new RegExp()); // false
isEmptyObject(new String()); // false
isEmptyObject(new Number()); // false
isEmptyObject(new Function()); // false
isEmptyObject(new Date()); // false
isEmptyObject(null); // false
isEmptyObject(undefined); // false
isEmptyObject({}); // true
I liked this one I came up with, with the help of some other answers here. Thought I'd share it.
Object.defineProperty(Object.prototype, 'isEmpty', {
get() {
for(var p in this) {
if (this.hasOwnProperty(p)) {return false}
}
return true;
}
});
let users = {};
let colors = {primary: 'red'};
let sizes = {sm: 100, md: 200, lg: 300};
console.log(
'\nusers =', users,
'\nusers.isEmpty ==> ' + users.isEmpty,
'\n\n-------------\n',
'\ncolors =', colors,
'\ncolors.isEmpty ==> ' + colors.isEmpty,
'\n\n-------------\n',
'\nsizes =', sizes,
'\nsizes.isEmpty ==> ' + sizes.isEmpty,
'\n',
''
);
It's weird that I haven't encountered a solution that compares the object's values as opposed to the existence of any entry (maybe I missed it among the many given solutions).
I would like to cover the case where an object is considered empty if all its values are undefined:
const isObjectEmpty = obj => Object.values(obj).every(val => typeof val === "undefined")
console.log(isObjectEmpty({})) // true
console.log(isObjectEmpty({ foo: undefined, bar: undefined })) // true
console.log(isObjectEmpty({ foo: false, bar: null })) // false
Example usage
Let's say, for the sake of example, you have a function (paintOnCanvas) that destructs values from its argument (x, y and size). If all of them are undefined, they are to be left out of the resulting set of options. If not they are not, all of them are included.
function paintOnCanvas ({ brush, x, y, size }) {
const baseOptions = { brush }
const areaOptions = { x, y, size }
const options = isObjectEmpty(areaOptions) ? baseOptions : { ...baseOptions, areaOptions }
// ...
}

Is "cancel" a keyword or reserved word in Photoshop?

Is "cancel" a keyword or reserved word?
My simple dialog box:
var dlg = new Window("dialog");
dlg.text = "Proceed?";
dlg.preferredSize.width = 160;
// GROUP1
// ======
var group1 = dlg.add("group", undefined, {name: "group1"});
group1.preferredSize.width = 160;
// add buttons
var button1 = group1.add ("button", undefined);
button1.text = "OK";
var button2 = group1.add ("button", undefined);
button2.text = "Cancel";
var myReturn = dlg.show();
if (myReturn == 1)
{
// code here
}
Works fine. All is well. However replace the string "Cancel" with "Can" and the button no longer functions.
You need to add extra code in order to regain functionality.
button2.onClick = function()
{
// alert("Byas!");
dlg.close();
dialogResponse = "cancel";
}
So, what's going on, is "cancel" a keyword?
"Cancel" is not a reserved word. If you change it to can, the dialog will return "can" if clicked (and not "cancel"). Maybe you need to update your code somewhere else to reflect it.
It works with your extra code because you're forcing the return of "cancel".

Updating react-table values after Dragging and Dropping a row in React Redux

IĀ“ve accomplished the react drag and drop functionality into my project so i can reorder a row in a react tableĀ“s list. The problem is i have a column named 'Sequence', witch shows me the order of the elements, that i canĀ“t update its values.
Example:
before (the rows are draggable):
Sequence | Name
1 Jack
2 Angel
after ( i need to update the values of Sequence wherea i change their position after dropping a specific draggable row, in this case i dragged Jack at the first position and dropped it at the second position) :
Sequence | Name
1 Angel
2 Jack
React/Redux itĀ“s allowing me to change the index order of this array of elements, without getting the 'A state mutation was detected between dispatches' error message, but is not allowing me to update the Sequence values with a new order values.
This is what i have tried so far:
// within the parent class component
// item is an array of objects from child
UpdateSequence(startIndex, endIndex, item) {
// the state.Data is already an array of object
const result = this.state.Data;
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
// this is working without the mutation state error
this.setState({ Data: result })
let positionDiff = 0;
let direction = null;
let newIndex = 0;
positionDiff = endIndex - startIndex;
if (startIndex > endIndex) {
direction = "up";
}
else if (startIndex < endIndex) {
direction = "down";
}
if (positionDiff !== 0) {
for (var x = 0; x <= Math.abs(positionDiff); x++) {
if (x === 0) {
newIndex = startIndex + positionDiff - x;
this.setState(prevState => ({
Data: {
...prevState.Data,
[prevState.Data[newIndex].Sequence]: Data[newIndex].Sequence + positionDiff
},
}));
}
else {
if (direction === "down") {
newIndex = startIndex + positionDiff - x;
this.setState(prevState => ({
Data: {
...prevState.Data,
[prevState.Data[newIndex].Sequence]: Data[newIndex].Sequence - 1
},
}));
}
else if (direction === "up") {
Data= startIndex + positionDiff + x;
this.setState(prevState => ({
Data: {
...prevState.Data,
[prevState.Data[newIndex].Sequence]: Data[newIndex].Sequence + 1
},
}));
}
}
}
// so when i call save action i am stepping into the 'A state mutation was detected between dispatches' error message.
this.props.actions.saveSequence(this.state.Data)
.then(() => {
this.props.actions.loadData();
})
.catch(error => {
toastr['error'](error, 'error....');
})
}
Calling the action 'saveSequence' whenever i try to update the element of the array, 'Sequence', i am getting the 'A state mutation was detected between dispatches' error message.
Any help will be greatfull! Thank you!
note: The logic applied to reorder the Sequence is ok.
While I don't know redux particularly well, I am noticing that you are directly modifying state, which seems like a likely culprit.
const result = this.state.Data;
const [removed] = result.splice(startIndex, 1);
splice is a destructive method that modifies its input, and its input is a reference to something in this.state.
To demonstrate:
> state = {Data: [1,2,3]}
{ Data: [ 1, 2, 3 ] }
> result = state.Data.splice(0,1)
[ 1 ]
> state
{ Data: [ 2, 3 ] }
Notice that state has been modified. This might be what Redux is detecting, and a general React no-no.
To avoid modifying state, the easy way out is to clone the data you are looking to modify
const result = this.state.Data.slice()
Note that this does a shallow copy, so if Data has non-primitive values, you have to watch out for doing destructive edits on those values too. (Look up deep vs shallow copy if you want to find out more.) However, since you are only reordering things, I believe you're safe.
Well, i figured it out changing this part of code:
//code....
const result = item;
const [removed] = result.splice(startIndex, 1);
// i created a new empty copy of the const 'removed', called 'copy' and update the Sequence property of the array like this below. (this code with the sequence number is just a sample of what i came up to fix it )
let copy;
copy = {
...removed,
Sequence: 1000,
};
result.splice(endIndex, 0, copy);
After i didnĀ“t setState for it, so i commented this line:
// this.setState({ Data: result })
//...code
and the end of it was putting the result to the save action as a parameter , and not the state.
this.props.actions.saveSequence(result)
Works and now i have i fully drag and drop functionality saving the new order sequence into the database with no more 'A state mutation was detected between dispatches' error message!

jqgrid - Add new row and disable restoreRow function

If I will add new row and I will enable automatic editing newly added row, then I want to perform validation and save row by ENTER button, BUT I don't want to restore row by ESC button. Because I set required: true by all fields and If newly added row will be to have empty at least one field, then ESC button (restoreRow) causes inconsistency my data, because will not be performed validation and newly added row will be to have empty fields. Although I set required: true.
The problem is that After added new row I always want to validate the edited row before saving, but ESC button causes restoreRow. For normal editing causes by doubliClick I want use ESC for restore row and ENTER for save row.
My code is generated from coffeescript
$("#add-row").click((function(_this) {
return function(e) {
e.preventDefault();
return _this.saveEditingRow(function() {
var dataIds;
_this.table.jqGrid("addRowData", void 0, "last");
dataIds = _this.table.jqGrid("getDataIDs");
if (dataIds.length > 0) {
return _this.table.jqGrid("editRow", dataIds[dataIds.length - 1], {
keys: true,
url: "clientArray",
aftersavefunc: function(rowId) {
return retypeColumnValues.call(table, rowId);
}
});
}
});
};
})(this));
Table.prototype.saveEditingRow = function(successfunc, errorfunc) {
var i, result, savedRows, success, _i, _ref;
savedRows = this.table.jqGrid("getGridParam", "savedRow");
success = true;
for (i = _i = 0, _ref = savedRows.length; _i < _ref; i = _i += 1) {
if (savedRows.length > 0) {
result = this.table.jqGrid("saveRow", savedRows[i].id, {
url: "clientArray"
});
if (!result && success) {
success = false;
}
}
}
if (success) {
return typeof successfunc === "function" ? successfunc() : void 0;
} else {
return typeof errorfunc === "function" ? errorfunc() : void 0;
}
};
If it will be necessary, I will fill all code in coffeescript.
I agree that it's a problem because the option keys: true register keydown event handler which process both Enter and Esc. You can't just inform jqGrid to process Enter, but don't process Esc.
If you don't call restoreRow in your code then you could probably salve your problem by usage of beforeCancelRow callback which you could define in $.jgrid.inlineEdit.
$.extend(true, $.jgrid.inlineEdit, {
beforeCancelRow: function () { // the parameters options and rowid can be used
return false;
}
});
The code above will don't allows restoreRow at all. You can modify the code by including some validations.
One more options which you have: don't use keys: true, but register your own keydown handler on all <input> and <select> fields in the editing row. You can do this inside of oneditfunc callback. See the source code of keydown handler used by jqGrid. You need just call of saveRow in case of e.keyCode === 13. The required rowid you can either get from the outer scope (if you do this inside of oneditfunc) or to get it from e.target: $(e.target).closest("tr.jqgrow").attr("id").
One more option: you can add some class like jqgrid-new-row (it's the class used by addRow method) to the row (<tr>) directly after call of addRowData ($("#" + dataIds[dataIds.length - 1]).addClass("jqgrid-new-row")). You should add afterrestorefunc callback to editRow which you call. Inside of the afterrestorefunc you can test whether the row has jqgrid-new-row class and call delRowData row in the case. By the way if you add the class with jqgrid-new-row name (or to use addRow instead of addRowData) then deleting of canceled row will be done automatically by restoreRow (see the code fragment).
You can even do this unconditionally without any tests for the class jqgrid-new-row if the above code work only in case of editing of new added row. So the call of editRow could be like below
return _this.table.jqGrid("editRow", dataIds[dataIds.length - 1], {
keys: true,
url: "clientArray",
aftersavefunc: function(rowId) {
return retypeColumnValues.call(table, rowId);
},
afterrestorefunc: function(rowId) {
_this.table.jqGrid("delRowData", rowId); // delete after cancel editing
}
});

How to get a jqGrid cell value when editing

How to get a jqGrid cell value when in-line editing (getcell and getRowData returns the cell content and not the actuall value of the input element).
General function to get value of cell with given row id and cell id
Create in your js code function:
function getCellValue(rowId, cellId) {
var cell = jQuery('#' + rowId + '_' + cellId);
var val = cell.val();
return val;
}
Example of use:
var clientId = getCellValue(15, 'clientId');
Dodgy, but works.
Here is an example of basic solution with a user function.
ondblClickRow: function(rowid) {
var cont = $('#grid').getCell(rowid, 'MyCol');
var val = getCellValue(cont);
}
...
function getCellValue(content) {
var k1 = content.indexOf(' value=', 0);
var k2 = content.indexOf(' name=', k1);
var val = '';
if (k1 > 0) {
val = content.substr(k1 + 7, k2 - k1 - 6);
}
return val;
}
After many hours grief I found this to be the simplest solution. Call this before fetching the row data:
$('#yourgrid').jqGrid("editCell", 0, 0, false);
It will save any current edit and will not throw if there are no rows in the grid.
As you stated, according to the jqGrid documentation for getCell and getRowData:
Do not use this method when you editing the row or cell. This will return the cell content and not the actual value of the input element
Since neither of these methods will return your data directly, you would have to use them to return the cell content itself and then parse it, perhaps using jQuery. It would be nice if a future version of jqGrid could provide a means to do some of this parsing itself, and/or provide an API to make it more straightforward. But on the other hand is this really a use case that comes up that often?
Alternatively, if you can explain your original problem in more detail there may be other options.
Try this, it will give you particular column's value
onSelectRow: function(id) {
var rowData = jQuery(this).getRowData(id);
var temp= rowData['name'];//replace name with you column
alert(temp);
}
Basically, you have to save the row before you access the cell contents.
If you do, then you get the value for the cell instead of the markup that comes when the cell is in edit mode.
jQuery.each(selectedRows, function(index, foodId) {
// save the row on the grid in 'client array', I.E. without a server post
$("#favoritesTable").saveRow(foodId, false, 'clientArray');
// longhand, get grid row based on the id
var gridRow = $("#favoritesTable").getRowData(foodId);
// reference the value from the editable cell
foodData += foodId + ":" + gridRow['ServingsConsumed'] + ',';
});
Hiļ¼Œ I met this problem too. Finally I solved this problem by jQuery. But the answer is related to the grid itself, not a common one. Hope it helps.
My solution like this:
var userIDContent = $("#grid").getCell(id,"userID"); // Use getCell to get the content
//alert("userID:" +userID); // you can see the content here.
//Use jQuery to create this element and then get the required value.
var userID = $(userIDContent).val(); // var userID = $(userIDContent).attr('attrName');
you can use this directly....
onCellSelect: function(rowid,iCol,cellcontent,e) {
alert(cellcontent);
}
This is my solution:
function getDataLine(grida, rowid){ //vykradeno z inineeditu a vohackovano
if(grida.lastIndexOf("#", 0) === 0){
grida = $(grida);
}else{
grida = $("#"+grida);
}
var nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;
ind = grida.jqGrid("getInd",rowid,true);
if(ind === false) {return success;}
editable = $(ind).attr("editable");
if (editable==="1") {
var cm;
var colModel = grida.jqGrid("getGridParam","colModel") ;
$("td",ind).each(function(i) {
// cm = $('#mygrid').p.colModel[i];
cm = colModel[i];
nm = cm.name;
if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
switch (cm.edittype) {
case "checkbox":
var cbv = ["Yes","No"];
if(cm.editoptions ) {
cbv = cm.editoptions.value.split(":");
}
tmp[nm]= $("input",this).is(":checked") ? cbv[0] : cbv[1];
break;
case 'text':
case 'password':
case 'textarea':
case "button" :
tmp[nm]=$("input, textarea",this).val();
break;
case 'select':
if(!cm.editoptions.multiple) {
tmp[nm] = $("select option:selected",this).val();
tmp2[nm] = $("select option:selected", this).text();
} else {
var sel = $("select",this), selectedText = [];
tmp[nm] = $(sel).val();
if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
$("select option:selected",this).each(
function(i,selected){
selectedText[i] = $(selected).text();
}
);
tmp2[nm] = selectedText.join(",");
}
if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
break;
}
}
});
}
return tmp;
}
I have a solution:
1. Using this.value to get the current editing value in the editing row.
2. Save the cell value to a hidden field when the cell lost its focus.
3. Read the hidden field when you need.
The code:
colModel="[
{ name: 'Net', index: 'Net', editable:true, editoptions: { dataEvents: [ { type: 'focusout', fn: function(e) {$('#HiddenNet').val(this.value);} }] }, editrules:{custom:true,}},
{ name: 'Tax', index: 'Tax', editable:true, editoptions: { dataEvents: [ { type: 'focus', fn: function(e) {this.value=$('#HiddenNet').val(); } }] }, editrules:{custom:true}}
]"
Good Luck
You can get it from the following way...!!
var rowId =$("#list").jqGrid('getGridParam','selrow');
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId']; // perticuler Column name of jqgrid that you want to access
In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.
var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents));
//in my case logs <h3>The Value I'm After</h3>
var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"
my answer is based on #LLQ answer, but since in my case my cellContents isn't an input I needed to use .text() instead of .val() to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.
its very simple write code in you grid.php and pass the value to an other page.php
in this way you can get other column cell vaue
but any one can make a like window.open(path to pass value....) in fancy box or clor box?
$custom = <<<CUSTOM
jQuery("#getselected").click(function(){
var selr = jQuery('#grid').jqGrid('getGridParam','selrow');
var kelr = jQuery('#grid').jqGrid('getCell', selr, 'stu_regno');
var belr = jQuery('#grid').jqGrid('getCell', selr, 'stu_school');
if(selr)
window.open('editcustomer.php?id='+(selr), '_Self');
else alert("No selected row");
return false;
});
CUSTOM;
$grid->setJSCode($custom);
I think an extension of this would get it for you.
retrieving-original-row-data-from-jqgrid
I think a better solution than using getCell which as you know returns some html when in edit mode is to use jquery to access the fields directly. The problem with trying to parse like you are doing is that it will only work for input fields (not things like select), and it won't work if you have done some customizations to the input fields. The following will work with inputs and select elements and is only one line of code.
ondblClickRow: function(rowid) {
var val = $('#' + rowid + '_MyCol').val();
}
I've got a rather indirect way. Your data should have an unique id.
First, setting a formatter
$.extend(true, $.fn.fmatter, {
numdata: function(cellvalue, options, rowdata){
return '<span class="numData" data-num="'+rowdata.num+'">'+rowdata.num+'</span>';
}
});
Use this formatter in ColModel. To retrieve ID (e.g. selected row)
var grid = $("#grid"),
rowId = grid.getGridPara('selrow'),
num = grid.find("#"+rowId+" span.numData").attr("data-num");
(or you can directly use .data() for latest jquery 1.4.4)
In order to get the cell value when in-line editing you need to capture this event(or another similar event, check documentation):
beforeSaveCell: function (rowid, celname, value, iRow, iCol) { }
In the value parameter you have the 'value' of the cell that was currently edited.
To get the the rest of the values in the row use getRowData()
I lost a lot of time with this, hope this helps.
My workaround is to attach an object containing orignal values to each tr element in the grid. I've used afterAddRecord callback to get my hands on the values before jqGrid throws them away and jQuery's "data" method to store them in the work.
Example:
afterInsertRow: function( rowid, rowdata, rowelem ) {
var tr = $("#"+rowid);
$(tr).data("jqgrid.record_data", rowelem);
},
ā€œrowelemā€ is the array of cell values from our JSON data feed or [jsonReader] (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#jsonreader_as_function)
Then at any point I can fetch those attributes using:
$(tr).data(ā€œjqgrid.record_dataā€).
More at: http://wojciech.oxos.pl/post/9423083837/fetching-original-record-values-in-jqgrid
I think that Aidan's answer is by far the best.
$('#yourgrid').jqGrid("editCell", 0, 0, false);
This commits any current edits, giving you access to the real value. I prefer it because:
You don't have to hard-code any cell references in.
It is particularly well suited to using getRowData() to get the entire grid, as it doesn't care which cell you've just been editing.
You're not trying to parse some markup generated by jqGrid which may change in future.
If the user is saving, then ending the edit session is likely the behaviour they would want anyway.
Before i was getting :
html tag of the textbox something like
but Here is the solution to get the value from that particular column, working and tested
function getValue(rowId, cellId) {
var val = $("[rowId='"+rowId+"'][name='"+cellId+"']").val();
return val;
}
var values = getValue(rowId, 'cellid');
I obtain edit value using javascript:
document.getElementById('idCell').value
I hope this info useful for someone.
I needed the original value before the formatter, so this is what I did:
{
name: 'Slot', title: false, formatter: function (cellValue, options, rowObject) {
rowObject['SlotID'] = cellValue; // <--- This saves the original ID
if (somelogic) {
return someString;
} else {
return someOtherString;
}
}
},
{ name: 'SlotID', hidden: true }
Now SlotID contains the original ID. Also, you don't need to have SlotID property on your original model.
try subscribing to afterEditCell event it will receive (rowid, cellname, value, iRow, iCol) where value is your a new value of your cell
You can use getCol to get the column values as an array then index into it by the row you are interested in.
var col = $('#grid').jqGrid('getCol', 'Sales', false);
var val = col[row];

Resources