Why does data in list1 changed automatically when I change the data in the other list2 which is cloned from the list1? Using Vue.Draggable - vue.js

I am using Vue.Draggable in my Vue project and trying to drag(clone) a button from sider into a draggable component.
I want to modify the data when I clone the button into the component. But I find that when I modify the data in the list which is binded with the component, the original list that sider used got changed automatically.
Is there some kind of synchronization mechanism in Vue.Draggable or something? I want to change the object data in the component only.
I tried to modify the object in the list2 manually by using a vue extension in Chrome browser. And it still happens. So I think maybe it's not bug in my code.
addEntity (conditionID, entity) {
if (!entity.forChoose) {
}
else {
let variable = 0;
for (let i = 0, len = this.whens.length; i < len; i++) {
if (this.whens[i].entity[0].id == entity.id) {
variable++;
}
}
this.whens[conditionID].entity[0].forChoose = false;
this.whens[conditionID].entity[0].variable = variable;
this.whens[conditionID].entity[0].name = entity.name + '-fake';
}
},
The code above is the event when I drag the data into the component, and changed some variable.
Although I did nothing to the original data in the Sider where I cloned the data from, it still got changed as well.
Is there a way to change the dragged data but do not affect the original data?
Please help me, thank you!

I think this is happening because of the immutability.
so can you try using spread operator to create new shallow copy of your list before you change it.
how to use spread operator (triple dot)
let newArrayOfWhens = [...this.whens]
then use the "newArrayOfWhens" array in your code
You can create a deep clone as well if you want, but try to avoid it if it is not necessary.
you can use a library call "lodash" to do it very easily
deepClone

Related

Add value at the beginning of an array in react-native hook

I am functional component I am using hooks to update the state of the array locationData
const c = {
title: inputValue,
}
setLocationData([...locationData, c]);
This is working fine, but now I want to add the value at the beginning of the array, and not at the end.
Edit:
I also have a problem to delete an item from the array. I want to delete one item, but more are deleted
const deleteItem = (index) => {
console.log(index)
var temp = locationData;
var temp = locationData.splice(index, 1);
setLocationData(temp);
}
You are almost there, just switch the position in the array.
setLocationData([c, ...locationData]);
You should also be aware of other methods like splice, slice, push, pop etc...
Update: Using Splice
This relates to part 2 of your question with regards to removing from specific index.
The splice() method changes the contents of an array by removing or
replacing existing elements and/or adding new elements in place. To
access part of an array without modifying it, see slice().
So your codes should be similar to the following
var temp = [...locationData];
temp.splice(index, 1);
setLocationData(temp);

MVVM pattern in NativeScript - how to use one?

The Problem
I just cannot figure out the view model in NativeScript
I am having a hard time understanding how view-models work in NativeScript. I understand the high level concept - that the MVVM pattern allows us to create observable objects - and our UI is updated when values change.
Here is a simple example:
main-page.js
var createViewModel = require("./main-view-model").createViewModel;
function onNavigatingTo(args) {
var page = args.object;
page.bindingContext = createViewModel();
}
exports.onNavigatingTo = onNavigatingTo;
main-view-model.js
var Observable = require("tns-core-modules/data/observable").Observable;
function getMessage(counter) {
if (counter <= 0) {
return "Hoorraaay! You unlocked the NativeScript clicker achievement!";
} else {
return counter + " taps left";
}
}
function createViewModel() {
var viewModel = new Observable();
viewModel.counter = 42;
viewModel.message = getMessage(viewModel.counter);
viewModel.onTap = function() {
this.counter--;
this.set("message", getMessage(this.counter));
}
return viewModel;
}
exports.createViewModel = createViewModel;
I understand , some what, what is happening. But not everything.
Questions I Have ...
How would you add a new function , for instance, an email validation function? Would it go into the View Model page, or just plain Javscript page?
Let's say I added a new textfield to the UI. I have a tap function. Where does my function go?
So in this case, everything related to the UI should go in the createViewModel function? Is that correct?
I have also seen in sample apps, where the developer doesn't use view models at all - it appears he just creates it as an observable object.
Thank you for looking. I know I am close to understanding, but that bindingContext and the viewmodel has me a bit confused. [ I have read everything in NS docs ]
John
The answer is either of it should work. You may put the validation or tap function in view model or in the code behind file, it's upto you to decide which works best for you.
If you put it in the view model, you will use event binding (tap="{{ functionName }}" Or if you put it in code behind file, you will just export the function name and simply refer the function name on XML (tap="functionName").
By giving this flexibility you are allowed to separate your code, keep the files light weighted.

bind dynamically to this vuejs

Hey guys I have the following function its working ok but I think it could be better.
methods: {
onFileChange(e, filedName) {
console.log(e.target.files);
console.log(filedName);
const file = e.target.files[0];
const fileToCheck=document.getElementById(filedName);
console.log(fileToCheck);
if(filedName=='thumbnail1'){
if(fileToCheck.value!=''){
this.thumbnail1 = fileToCheck;
this.thumbnail1Url= URL.createObjectURL(file);
} else {
this.thumbnail1=null;
this.thumbnail1Url=null;
}
}
if(filedName=='thumbnail2'){
if(fileToCheck.value!=''){
console.log(fileToCheck);
this.thumbnail2=fileToCheck;
this.thumbnail2Url = URL.createObjectURL(file);
} else {this.thumbnail2=fileToCheck; this.thumbnail2Url=null;}
}
},
Instead of checking the value for
if(fieldName == "something"){
this.something = URL.createObjectURL(file)
}
I would simply pass in a string of the fieldName and bind to it dynamically by just typing this.fieldName (filedName could equal thumbnail1 or thumbnail2 or chicken for all I care I just want to be able to pass in the name of the data atrribute and bind to it that way) but when ever I do this it doesn't work. Any help here would be great.
It's not completely clear to me what you want to accomplish, but I think you're asking about creating a dynamic data property for a view component. If that's the case, there are a couple of things to consider.
First, the example you cite, this.fieldName is not correct JavaScript syntax if fieldName is a string that contains a property name. The correct version is this[fieldName].
Note, though, that you can't simply define a new data property for a Vue component by setting it to a value. That's a limitation of JavaScript that's described in the Vue documentation. If data[fieldName] is an existing property that's defined in the component's data object, then you'll be okay. Even if you don't know the value of the property, you can initialize it, for example, with a value of null and then update the value in your method. Otherwise, you'll need to add the property to an existing non-root-level property as the documentation explains.

extjs 4.1 how to reset the itemselector

I am using extjs 4.1.1a for developing some application.
I had a form consisting of two combo-boxes and an item-selector.
Based on the value selected in first combo-box , the itemselector will load its data from database. This is working fine.
My problem is, if i reselect the first combo-box the new data will be displayed in itemselector along with previous data displayed in itemseletor .That is previous data displayed in itemselector will remain there itself.
for example: name "test1" consists of ids 801,2088,5000. on selecting test1 in firstcombobox itemselector must show output as below.
and if "test2" consists of ids 6090,5040. on selecting test2 in firstcombobox itemselector must show output as below.
problem is. for first time if i select "test1" from firstcombobox , output will come as expected. if i reselect "test2" from firstcombobox , output will come as below.
as you can see, previous data displayed (marked in red rectagle) remains there itself with new data displayed (marked with green rectangle).
I want for every reselection of first combobox, previously displayed data in itemselector to be erased before printing new data on itemselector.
How can I reset the itemselector for every reselection of first combobox?
You should remove all items from the store of the itemselector by the removeAll command. After that you should load the store of the itemselector.
itemselector.store.removeAll();
itemselector.store.load();
Any solutions above solve my problem.
i found solution from Sencha Forum.
https://www.sencha.com/forum/showthread.php?142276-closed-Ext-JS-4.0.2a-itemselector-not-reloading-the-store
in the itemselector.js file, change the line marked below.
populateFromStore: function(store) {
var fromStore = this.fromField.store;
// Flag set when the fromStore has been loaded
this.fromStorePopulated = true;
// THIS LINE BELOW MUST BE CHANGED!!!!!!!!!!!!
fromStore.loadData(store.getRange()); //fromStore.add(store.getRange());
// setValue waits for the from Store to be loaded
fromStore.fireEvent('load', fromStore);
},
You need to insert...
this.reset();
at the head of the function that is inserting the data.
As an example...
Ext.override( Ext.ux.ItemSelector, {
setValue: function(val) {
this.reset();
if (!val) return;
val = val instanceof Array ? val : val.split(this.delimiter);
var rec, i, id;
for (i = 0; i < val.length; i++) {
var vf = this.fromMultiselect.valueField;
id = val[i];
idx = this.toMultiselect.view.store.findBy(function(record){
return record.data[vf] == id;
});
if (idx != -1) continue;
idx = this.fromMultiselect.view.store.findBy(function(record){
return record.data[vf] == id;
});
rec = this.fromMultiselect.view.store.getAt(idx);
if (rec) {
this.toMultiselect.view.store.add(rec);
this.fromMultiselect.view.store.remove(rec);
}
}
}
});
are u got it?
when u select that combobox frist stoe of item selector is null after store load with ur pass the para meters
for example
store.load(null),
store.proxey.url='jso.php?id='+combobox.getrawvalue(),
store.load();
like that so when ur select a value in ur combobox that time ur used a listeners to ur combobox in that listners ur used above code , select ur some value in combobox that time frist store is get null after ur pass some values to json.php then store load with responce so that time old data is remove and new data load in that store
if u post ur code i will give correct code
I ran into the same issue with ExtJS 4.2.1. I got it to work by calling reload() on the data store and then setValue() with an empty string on the item selector in the data store's reload() callback.
Ext.create("Ext.form.field.ComboBox", {
// Other properties removed for brevity
listeners: {
change: function(field, newValue, oldValue, eOpts) {
Ext.getStore("ExampleStore").reload({
callback: function() {
Ext.getCmp("ExampleItemSelector").setValue("");
}
});
}
}
});
Ext.create("Ext.data.Store", {
storeId: "ExampleStore",
// Other properties removed for brevity
});
Ext.create("Ext.form.FormPanel", {
// Other properties removed for brevity
items:[{
xtype: "itemselector",
id: "ExampleItemSelector",
// Other properties removed for brevity
}]
});
For any folks that are curious, I'm fairly convinced there's a bug in the item selector's populateFromStore() function. When the function is called, it blindly adds all of the values from the bound store (store) to the internal store (fromStore). I suspect there should be a call to fromStore.removeAll() prior to the call to fromStore.add(). Here's the relevant code from ItemSelector.js.
populateFromStore: function(store) {
var fromStore = this.fromField.store;
// Flag set when the fromStore has been loaded
this.fromStorePopulated = true;
fromStore.add(store.getRange());
// setValue waits for the from Store to be loaded
fromStore.fireEvent('load', fromStore);
},
EDIT 12/18/2013
If you've configured any callback events on the item selector (e.g. change), you may want to disable the events temporarily when you call setValue(""). For example:
var selector = Ext.getCmp("ExampleItemSelector");
selector.suspendEvents();
selector.setValue("");
selector.resumeEvents();
I had the same problem and finally I decided to modify the extjs source code, not considering it a big issue as extjs itself its saying in the start of the file
Note that this control will most likely remain as an example, and not as a core Ext form
control. However, the API will be changing in a future release and so should not yet be
treated as a final, stable API at this time.
Based on that, as jstricker guessed (and sadly I didn't read and took me a while to arrive to the same conclusion), adding fromStore.removeAll() before fromStore.add() solves the problem.
Outside of the problem (but I think it can be interesting as well), additionally, I also added listConfig: me.listConfig in the MultiSelect configuration (inside createList), that way it's possible to format each item additional options (such as images, etc.) setting in the 'itemselector' the option listConfig as it's explained in the (irrealistic) documentation.
Need to reset the store used in ItemSelector that can be done by setting Empty object like below. Also need to call clearValue() method of ItemSelector component.
store.setData({});
ItemSelectorComponent.clearValue();

How to refresh datagrid

I create dojox.grid.datagrid and I fill content from array like on example last example on page. During time, I change value of that array in code. How to refresh content of that grid ? How to load new data from changed array ?
To change values in the grid, you will need to change the value in the grid's store. The grid data is bound to the store data, and the grid will update itself as needed.
So the key is to understand Dojo's data api and how stores work in Dojo. Rather than manipulating the data directly in the grid, manipulate it in the store.
Ideally, the store is your array that you manipulate as the application runs and you should not be needing to sync the array to the grid. Just use the ItemFileWriteStore as your data holder unless thats not possible.
Also, using the dojo data identity api makes it much simple to find items in the grid if that is possible. Assuming you know when an item is updated, deleted, or changed in your application you should be able to modify the grid store as needed when the action happens. This is definitely the preferred approach. If you can't do that you will have to do a general fetch and use the onComplete callback to manually sync your arrays which will be very slow and won't scale well, in which case you may as well just create a new store all together and assign it to the grid with grid.setStore(myNewStore)
Here is a fiddle with a basic create, update, and delete operation: http://jsfiddle.net/BC7yT/11/
These examples all take advantage of declaring an identity when creating the store.
var store = new dojo.data.ItemFileWriteStore({
data: {
identifier : 'planet',
items: itemList
}
});
UPDATE AN EXISITNG ITEM:
//If the store is not in your scope you can get it from the grid
var store = grid.store;
//fetchItemByIdentity would be faster here, but this uses query just to show
//it is also possible
store.fetch({query : {planet : 'Zoron'},
onItem : function (item ) {
var humans = store.getValue(item, 'humanPop');
humans += 200;
store.setValue(item, 'humanPop', humans);
}
});
INSERT A NEW ITEM:
store.newItem({planet: 'Endron', humanPop : 40000, alienPop : 9000});
} catch (e) {
//An item with the same identity already exists
}
DELETE AN ITEM:
store.fetchItemByIdentity({ 'identity' : 'Gaxula', onItem : function (item ) {
if(item == null) {
//Item does not exist
} else {
store.deleteItem(item);
}
}});
The following code snippet can be used to update the grid:
var newStore = new dojo.data.ItemFileReadStore({data: {... some new data ...});
var grid = dijit.byId("gridId");
grid.setStore(newStore);
EDIT:
Dogo data grid reference guide (add/remove rows example, updating grid data examples )
(I suppose you already have a working grid and you want to completely change the grid's store)
Create a new datastore with your new value :
dataStore = new ObjectStore({ objectStore:new Memory({ data: data.items }) });
(data is the reponse from an ajax request for me)
Change your grid's store with the new one :
grid.store = dataStore;
Render :
grid.render();
This Will update Grid Store and refresh the View of the Grid in latest Version of Dojo 1.9
grid.store = store;
grid._refresh();
I had a server-side filtered EnhancedGrid, which was refreshing happily by changing the store, and shown in the other answers.
However I had another EnhancedGrid that would not refresh when a filter was applied. It may have been to do with the fact it was filtered client side (but data still coming from server using JsonRest store), but I don't really know the cause. Eitherway, the solution was to refresh with the following code:
grid.setFilter(grid.getFilter());
It's hacky and strange, but if it all else fails...
with this i can update a specifi row. this example is for a treegrid.
var idx = this.treeGrid.getItemIndex(item);
if(typeof idx == "string"){
this.treeGrid.updateRow(idx.split('/')[0]);
}else if(idx > -1){
this.treeGrid.updateRow(idx);
}