Add records to Ext.data.ArrayStore - javascript

How can I add the following records (from the alert) into the Ext.data.ArrayStore? The commented out code (in newStore assignment) shows what data is set in the store originally and seems to work. The code in the loop shows what I've tried that did not work.
var newStore = new Ext.data.ArrayStore({
fields: [
'id',
'value'
]
//data: [[1, 'x'], [2, 'y']]
});
//alert(records.toSource());
Ext.each(records, function(rec) {
alert(rec.get('id') + ' ... ' + rec.get('value'));
//newStore.data.add(rec);
//Ext.apply(newStore, rec);
});

The .add() expect a record object. If your objects in the Ext.each() are in the format
{
id:"~~",
value:"~~"
}
simply calling newStore.add(rec); will work just fine.
If they are not you will need to build a psudo record by doing something like this:
Ext.each(records,function(rec){
newStore.add({id:rec.id,value:rec.value});
}
Here is a fiddle of a working example
http://jsfiddle.net/7a86L/

var arrayData = [
['Jay Garcia', 'MD'],
['Aaron Baker', 'VA'],
['Susan Smith', 'DC'],
['Mary Stein', 'DE'],
['Bryan Shanley', 'NJ'],
['Nyri Selgado', 'CA']
];
var store = Ext.create('Ext.data.ArrayStore', {
data : arrayData,
fields : ['personName', 'state']
});
console.log(store.first().data)

Related

Filter duplicate values in select2 ajax call

I'm using select2 load remote data way to render results (50 at a time) from an api. The response of the api might have duplicate values in any page response.
I have tried formatting response but unfortunately the method is having access only to the current page data.
Below is my code,
jQuery('#items').select2({
minimumInputLength : 2,
placeholder : '-- Select Items --',
ajax : {
url : '/api/v1/items',
quietMillis : 200,
dataType : 'json',
data : function (term, page) {
return {
term : term,
page : page,
page_limit : 50
};
},
results : function(data, page) {
//Here I'm getting only current page data. How can i get previous page data to check for duplicate values.
}
}
});
So, how can I filter the response and eliminate duplicate values by checking against the data fetched so far.
Any help would be appreciated.
It would be better if you post an example of your code. Let's say you have some data with duplicated entries:
var rawData = [
{
id: 'AL',
name: 'Alaska'
},
{
id: 'GE',
name: 'Georgia'
},
{
id: 'WY',
name: 'Wyoming'
},
{
id: 'GE',
name: 'Georgia'
}
];
function clearDuplicates(data) {
var temp = {};
for (var i = 0; i < data.length; i++) {
temp[data[i]['id']] = data[i];
}
return Object.values(temp);
}
var clearData = clearDuplicates(rawData);
console.log(clearData);
See output: duplicated entry 'Georgia' is now in one record. There can be a lot of ways to eliminate duplicates. This is just one simple example.
UPDATE:
If you use pagination (infinite scroll) in Select2, every page request is sent separately and you have to process result data and eliminate duplicates manually. it can be done by processResults parameter. (See example)
In that case, easiest way would be:
Handle every page request in processResults
Store all results in a global variable
Eliminate duplicates as described in the example above
Return desired result
Return:
return {
results: <YOUR_FILTERED_DATA>,
pagination: {
//paginatioin params
}
}

How to send data from jquery to javascript

<script>
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
alert("state data"+data);
});
</script>
I have the value in data and want to show in javascript given below.
The fields data is given want to push my state data there.
<script>
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
</script>
Both are written in diffrent script
datasets is an array with an object on index 0. So to define or redeclare the data property in there the syntax is
salesChartData.datasets[0].data = data;
Use it in your callback function:
function(data) {
salesChartData.datasets[0].data = data;
});
Not sure if I understand correctly, is this what you need?
var salesChartData = {
datasets: [
{
data : {}
}
]
};
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
salesChartData.datasets[0].data = data;
});
Just set the data after receiving it
if you need to show the ajax result in a variable salesChartData, you can try this
salesChartData.datasets[0].data[0] = "new data"
salesChartData is a JSON object with key datasets contains an array of JSON objects.
So if salesChartData is declared globally, then you can replace in the success of the ajax
Here below, it done using web storage. This is used to access from different file.
// File 1
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
localStorage.setItem("salesChart", JSON.stringify(salesChartData));
//-----------------------------------------------------------------------
// File 2
var salesChartData = JSON.parse(localStorage.getItem("salesChart"));
// ajax call
$.getJSON('chartState', {
stateCode: $(this).val(),
ajax: 'true'
},
function (data) {
alert("state data" + data);
salesChartData.datasets[0].data[0] = data // "new data"
});
Hope this will work.
Thank You
I have done with my self
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
var chr=data;
var a=chr[0];var b=chr[1];var c=chr[2];var d=chr[3];
var e=chr[4];var f=chr[5];var g=chr[6];
After that I have sended one by one data
var salesChartData = {
datasets: [
{
data : [g,f,e,d,c,b,a]
}
]
};
As you mention that both parts of the script are in different tags you can solve the problem with a global, this is not recommended. The better solution would be to refactor the structure and not have multiple script tags. But if you have no control over this then you should do something like this:
<script>
// No var used to make it global
chart_state_data = false;
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
// the data is set to this variable on callback
chart_state_data = data
});
</script>
And:
<script>
// chart_state_data contains data retrieved from ajax call or false
var salesChartData = {
datasets: [{
data: chart_state_data
}]
};
</script>

I want to use JsArray with the Webix component DataTable

I want to use JsArray with the Webix component DataTable. But I have one problem. When I use JsArray format I can’t update the data in the Webix datagrid. Unfortunately, I can see only the beginning of its data. Check the sample to understand the issue:
var array1 = [ [1,"Marie","Oslo"],[2,"John","Los Angeles"],[3,"Kate","London"] ];
var array2 = [ [4,"Martin","Manchester"],[5,"Joana","Lisbon"],[6,"Ronaldo","Barcelona"],[7,"Matthew","Portland"] ];
webix.ui({
view:"button",
label:"test new data",
click: function() {
new_data()
}
});
webix.ui({
view:"datatable",
id: "mytable",
columns:[
{id:"data0", header:"ID" },
{id:"data1", header:"Name" },
{id:"data2", header:"City" }
],
datatype: "jsarray",
data: array1
});
function new_data () {
var mytable = $$("mytable");
mytable.parse(array2);
}
After pressing the button “test new data”, 4 new empty lines appear in the table.
To solve this issue, you should specify data format in the parse command
mytable.parse(array2, "jsarray");
The component will expect the json data, by default.
I hope that it'll help you)

Using collection helpers in meteor tabular

I'm displaying table data using Meteor aldeed:tabular
The tabular initialization code is simple:
this.TabularTables.Customers = new Tabular.Table({
name: "Clients",
collection: this.Customers,
columns: [
{data: "lastName", title: "Name"},
{data: "myMessage()", title: "Message"}
],
});
First field, lastName works perfectly, but adding second field myMessage() causes the problem
I installed dburles:collection-helpers extension and add helper in common code section:
this.Customers = new Mongo.Collection("customers");
this.Customers.helpers({
myMessage: function () {
return "Hi!";
}
});
But still getting error on the client side:
Exception from Tracker recompute function:
debug.js:41 TypeError: a[i[j]] is not a function
at c (jquery.dataTables.min.js:16)
at jquery.dataTables.min.js:17
What might be the problem with my helper function and where should I declare it?
I've done more or less exactly what you have done and it works nicely.
Countries = new Mongo.Collection('countries');
TabularTables = {};
Meteor.isClient && Template.registerHelper('TabularTables', TabularTables);
TabularTables.Countries = new Tabular.Table({
name: "CountriesList",
collection: Countries,
columns: [
{data: 'italian_name', title: 'Italian name'},
{data: 'catalogueName',title: 'Catalogue name'},
{data: "myFunction()", title: 'Wot'}
]
});
Countries.helpers({
myFunction: function () {
return "Hi!";
}
});
The only real difference I can see is this line:
Meteor.isClient && Template.registerHelper('TabularTables', TabularTables);
Finally I found the problem: TabulatTables use collection transformer dburles:collection-helpers to call necessary function, but it confilcts with perak:joins that defines his own helpers

Refreshing gridx with server-side data

I'm thinking that I am overlooking something simple - I am so close to making this work. :)
I have a grid that needs to be updated with server information.
Here is the way that it should work:
A user selects an item
Make a JsonRest query with the item ID selected
Update the grid - showing notes relating to item selected
Here is how the grid is setup:
function noteTabSetup() {
var store = JsonRest({target:"//localhost/program/notes", idAttribute:"id"});
var structure = [{ field: 'id', name: 'Id', width: '5em' },
{ field: 'name', name: 'Name', width: '12%' },
{ field: 'description', name: 'Description' }];
var noteGrid = new Grid({
id: 'noteGrid',
pageSize: 20,
store: store,
cacheClass: Cache,
structure: structure,
filterServerMode: true,
selectRowTriggerOnCell: true,
bodyLoadingInfo: "Loading notes ...",
bodyEmptyInfo: "No notes found",
modules: [SingleSort, VirtualVScroller, moveColumn,
selectColumn, dndColumn, selectRow, Filter]}, noteTab);
noteGrid.startup();
When an item is selected, the selected item ID is passed to:
function noteLoad(itemId) {
console.log("In NoteLoad");
var grid = registry.byId("noteGrid");
if (!itemIds || 0 === itemIds.length) { console.log("no ItemId chosen"); }
else {
console.log("In NoteLoad with an itemId");
grid.model.clearCache();
// Error on second run
grid.store.query({ find: "ByItem", item: itemId }).then(function(result) {
grid.setStore(new ItemFileReadStore({data: {items : result}}));
});
grid.body.refresh();
console.log("model: " + grid.rowCount());
};
};
On the first item selected, everything works well - the query fires, and the grid is updated with notes related to the selected item.
On the second item selected, I receive this error from firebug:
TypeError: grid.store.query is not a function
grid.store.query({ find: "ByItem", item: itemIds }).then(function(result) {
-----------------------------------^
Any ideas?! Thank you in advance.
Chris
Thank you for the reply - that makes sense that store was being replaced by ItemFileReadStore. If possible, I would like to use JsonRest directly to update the grid.
I've tried a handful of variations based off of your comment, without luck:
Query fires and result is returned. Grid is not updated:
grid.model.clearCache();
grid.store.query({ find: "ByItem", item: itemIds }).then(function(results){
console.log('notes: ' + results[0].name);
});
grid.body.refresh();
Error: grid.store.fetch is not a function:
grid.store.fetch({ query: { find: "ByItem", item: itemIds }});
Syntax error in Dojo.js (line 15):
grid.store.query({ find: "ByItem", item: itemIds }).then(function(result) {
grid.setStore(new JsonRest({data: {items : result}}));
});
I've done a lot of searches and can't find a good example where the grid is being updated from a JsonRest object. Thank you.
Because the code itself replaces the store the first time.
grid.store.query({ find: "ByItem", item: itemId }).then(function(result) {
grid.setStore(new ItemFileReadStore({data: {items : result}}));
});
Here, the grid's store is initially JsonRest store, which after the query method is run, is replaced by the new ItemFileReadStore object. The mistake here is "query" is not a method of ItemFileReadStore, but the parameter passed to the "fetch" method. Check out some examples from dojo documentation on this.
On the other hand, JsonRest store has the method "query". Hence the contradiction. Change your code accordingly if you want ItemFileReadStore.
eg:-
store.fetch( { query: { name: 'Ice cream' },
onItem: function(item) {
console.log( store.getValue( item, 'name' ) );
console.log( 'cost: ', store.getValue( item, 'cost' ) );
}
});

Categories

Resources