Sencha Touch Maintain Different Stores From Same Json - sencha-touch

I would like to be able to maintain different stores from the same json where the model for each store is the same. Each store would need to be updated based on its root property assignment. Please see below for a sample json, store, and model, in which case each store would be updated based on the json's root property value (category 1, category 2, etc.). The goal is to be able to bind a nested list in my application to different stores on the fly, rather than call setProxy to change the url setting on a single store. Also, the json needs to be in this format. Thanks for your help and please let me know if I can provide clarification or answer any questions.
Json:
{
"items": [
{
"name": "category 1",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"leaf": true
}
]
}
]
}
]
},
{
"name": "category 2",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"leaf": true
}
]
}
]
},
{
"name": "cateory 3",
"status": "",
"displaytext": "",
"items": []
},
{
"name": "category 4",
"status": "",
"displaytext": "",
"items": []
}
]
}
Model:
Ext.define('MyApp.model.myModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'name',
type: 'string'
},
{
name: 'status',
type: 'string'
},
{
name: 'displaytext',
type: 'string'
}
]
}
});
Store 1, 2, 3, etc:
Ext.define('MyApp.store.storeCategory1', {
extend: 'Ext.data.TreeStore',
requires: [
'MyApp.model.myModel'
],
config: {
model: 'MyApp.model.myModel',
storeId: 'myStore',
autoLoad: false,
proxy: {
type: 'ajax',
url: '/path/to/file.json',
reader: {
type: 'json',
rootProperty: 'items'
}
}
}
});

I think you best bet would be to make a server request independent of the Store's proxy. On success, split up the data into the different stores as needed. It's fine to preprocess data this way, especially if you need to split one large data response into multiple data stores. For example:
Ext.Ajax.request({
url: 'path/to/file.json',
success: function(response){
// process server response here
var json = Ext.decode(response.responseText);
for(var i=0, l=json.items.length, i<l; i++){
// start distributing the data to your different stores here
}
}
});
Hope this helps.

Related

Realm sync not working for embedded objects in react native

This is my collection schema on realm -
{
"title": "testnote",
"properties": {
"_id": {
"bsonType": "objectId"
},
"_syncPartition": {
"bsonType": "string"
},
"title": {
"bsonType": "string"
},
"description": {
"bsonType": "string"
},
"subject": {
"bsonType": "string"
},
"tags": {
"bsonType": "array",
"items": {
"bsonType": "string"
}
},
"pages": {
"bsonType": "array",
"items": {
"title": "notespage",
"bsonType": "object",
"properties": {
"type": {
"bsonType": "string"
},
"data": {
"bsonType": "string"
}
}
}
},
"createdBy": {
"bsonType": "string"
}
}
}
This is how I've declared realm schema in react native. The code to initialize the Realm connection is also added below.
static NotesPage = {
name: "notespage",
embedded: true,
properties: {
type: "string",
data: "string"
}
}
static mainSchema = {
name: "testnote",
properties: {
_id: "objectId?",
_syncPartition: "string?",
createdBy: "string?",
title: "string?",
description: "string?",
subject: "string?",
tags: "string[]",
pages: { type: "list", objectType: "notespage" }
},
primaryKey: "_id"
};
const sampleNotesConfig = {
schema: [mainSchema NotesPage],
sync: {
user,
partitionValue: notesPartition,
newRealmFileBehavior: OpenRealmBehaviorConfiguration,
existingRealmFileBehavior: OpenRealmBehaviorConfiguration
}
};
Realm.open(sampleNotesConfig).then((notesRealm) => {
//// Some relevant code
}).catch((reason) => {
console.log("Error initializing realm");
console.log(reason);
});
When I create the realm object, it gets inserted in the local realm file but never gets synced to the server. I don't see any server errors or errors in local.
notesRealm.write(() => {
notesRealm.create(
SampleNote.schema.name,
{
"subject": "History",
"title": "Local to Remote Note 10",
"description": "Local to Remote Note 10 Description",
"tags": ["Tag 1", "Tag 2", "Tag 3"],
"pages": [{"type": "COVER_PAGE", "data": "Data 1"}, { "type": "PARAGRAPH", "data": "Data 2"}]
});
});
I have checked following things -
Partition values are correct.
User has permission to read/write to that partition.
If I just remove the pages section from the schema, the object starts syncing.

How to specify rootProperty for nested data if it is one level below?

I am fetching nested data to be shown as nested list but whenever I tap on top level item, it again shows same top level list instead of showing children list and a ajax request is fired to fetch json data again. Here is the store:
Ext.define('MyTabApp.store.CategoriesStore',{
extend:'Ext.data.TreeStore',
config:{
model : 'MyTabApp.model.Category',
autoLoad: false,
storeId : 'categoriesStore',
proxy: {
type: 'ajax',
url: 'resources/data/catTree.json',
reader: {
type: 'json',
rootProperty: 'data.categories'
}
},
listeners:{
load: function( me, records, successful, operation, eOpts ){
console.log("categories tree loaded");
console.log(records);
}
}
}
});
and here is the data in that file which I am using to mock service:
{
"data":{
"categories": [
{
"name": "Men",
"categories": [
{
"name": "Footwear",
"categories": [
{ "name": "Casual Shoes", "leaf": true },
{ "name": "Sports Shoes", "leaf": true }
]
},
{
"name": "Clothing",
"categories": [
{ "name": "Casual Shirts", "leaf": true },
{ "name": "Ethnic", "leaf": true }
]
},
{ "name": "Accessories", "leaf": true }
]
},
{
"name": "Women",
"categories": [
{ "name": "Footwear", "leaf": true },
{ "name": "Clothing", "leaf": true },
{ "name": "Accessories", "leaf": true }
]
},
{
"name": "Kids",
"categories": [
{
"name": "Footwear",
"categories": [
{ "name": "Casual Shoes", "leaf": true },
{ "name": "Sports Shoes", "leaf": true }
]
},
{ "name": "Clothing", "leaf": true }
]
}
]
}
}
This is the list:
Ext.define('MyTabApp.view.CategoriesList', {
extend: 'Ext.dataview.NestedList',
alias : 'widget.categorieslist',
config: {
height : '100%',
title : 'Categories',
displayField : 'name',
useTitleAsBackText : true,
style : 'background-color:#999 !important; font-size:75%',
styleHtmlContent : true,
listConfig: {
itemHeight: 47,
itemTpl : '<div class="nestedlist-item"><div>{name}</div></div>',
height : "100%"
}
},
initialize : function() {
this.callParent();
var me = this;
var catStore = Ext.create('MyTabApp.store.CategoriesStore');
catStore.load();
me.setStore(catStore);
}
});
The list starts working properly without any ajax request on each tap if I remove data wrapper over top categories array and change rootProperty to categories instead of data.categories. Since server is actually returning categories in data object I cannot remove it so how do I fix the store in that case? Also why is that additional ajax request to fetch the file?
[EDIT]
Tried to create a fiddle http://www.senchafiddle.com/#d16kl which is similar but not same because it is using 2.0.1 and data is not loaded from external file or server.
Last time I had this exact situation, it was because one of my top level category was a leaf but I had not set leaf:true. Doing so recalled the top level of the nested list as if it was a child.
It seems from your Fiddle that if your data is in this following format, it would work fine:
{
"categories" : [{
"name" : "Foo",
"categories" : [{
...
}]
}]
}
That is, just remove the "data" property and make defaultRootProperty: 'categories' & rootProperty: 'categories'. Check this: http://www.senchafiddle.com/#d16kl#tIhTp
It works with external data file as well.

Proper use of the rootProperty in Sencha Touch 2

I am trying to use the rootProperty value in a Sencha Touch 2 store to load some JSON I retrieved from the Foursquare Venues API and for the life of me I cannot get it to work.
According to the docs I should setup my rootProperty in dot notation to equal "response.venues" but it does not populate the list. I put the json in a separate file and removed the "response" and "venues" headers and it worked fine. There must be something blatantly obvious I'm missing here as I can't find a straight answer anywhere.
My model:
Ext.define('App.model.4SqVenue', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'name', id: 'id'}
]
}
});
My store:
Ext.define('App.store.4SqVenues', {
extend: 'Ext.data.Store',
requires: [
'App.model.4SqVenue'
],
config: {
model: 'App.model.4SqVenue',
storeId: '4SqVenuesStore',
proxy: {
type: 'jsonp',
url: 'foursquare venue request',
reader: {
type: 'json',
rootProperty: 'response.venues'
}
}
}
});
My view:
Ext.define('App.view.4SqVenues', {
extend: 'Ext.List',
xtype: '4SqVenuesCard',
requires: [
'App.store.4SqVenues'
],
config: {
fullscreen: true,
itemTpl: '{name}',
store: '4SqVenuesStore'
}
});
The response from the 4sq API:
{
"meta": {
"code": 200
},
"response": {
"venues": [
{
"id": "4a3ad368f964a52052a01fe3",
"name": "Four Peaks Brewing Company",
"contact": {
"phone": "4803039967",
"formattedPhone": "(480) 303-9967",
"twitter": "4PeaksBrewery"
},
"location": {
"address": "1340 E 8th St",
"crossStreet": "at Dorsey Ln.",
"lat": 33.4195052281187,
"lng": -111.91593825817108,
"distance": 1827,
"postalCode": "85281",
"city": "Tempe",
"state": "AZ",
"country": "United States"
},
"categories": [
{
"id": "4bf58dd8d48988d1d7941735",
"name": "Brewery",
"pluralName": "Breweries",
"shortName": "Brewery",
"icon": {
"prefix": "https://foursquare.com/img/categories/nightlife/brewery_",
"sizes": [
32,
44,
64,
88,
256
],
"name": ".png"
},
"primary": true
}
],
"verified": true,
"stats": {
"checkinsCount": 24513,
"usersCount": 8534,
"tipCount": 235
},
"url": "http://www.fourpeaks.com",
"likes": {
"count": 0,
"groups": []
},
"menu": {
"type": "foodAndBeverage",
"url": "https://foursquare.com/v/four-peaks-brewing-company/4a3ad368f964a52052a01fe3/menu",
"mobileUrl": "https://foursquare.com/v/4a3ad368f964a52052a01fe3/device_menu"
},
"specials": {
"count": 0,
"items": []
},
"hereNow": {
"count": 1,
"groups": [
{
"type": "others",
"name": "Other people here",
"count": 1,
"items": []
}
]
}
}
]
}
}
I have a very similar issue. Basically all is good if I load the json without the rootProperty defined. But once I define it things stop working (bad configuration error reported in Architect).
So the belwo works opnlu until I define the rootProperty as 'records'
{ "records" : [ { "artist" : "Champion",
"index" : 1,
"recordid" : "r00899659",
"trackname" : "1 To 2"
},
{ "artist" : "Champion",
"index" : 2,
"recordid" : "r00899668",
"trackname" : "Is Anybody There?"
}
.......
],
"rowcount" : 10,
"timestamp" : "1/07/2012 5:05:19 AM"
}
first, you have to wrap it in a function call as Per documentation for the response. Then you may have to use a convert function inside your model. Such as setting the root property to response, and then using convert to bring in all the other data from the venue property.

Sencha Touch JSONPReader

Using sencha touch 2, am trying to render a nestedlist with json proxy.
The json looks like
[
{
"start": "0"
},
{
"format": "json"
},
.......
{
"GetFolderListing": [
{
"folder": {
"total": 0,
"id": "Calendar",
"name": "Calendar",
"unread": 0,
}
},
{
"folder": {
"total": 0,
"id": "Contacts",
"name": "Contacts",
"unread": 0,
}
},
.......
I want to use GetFolderListing.folder.name as the displayField
My store looks like
Ext.define('foo.store.FolderListing', {
extend: 'Ext.data.TreeStore',
require: ['foo.model.FolderListing'],
config: {
model: 'foo.model.FolderListing',
recursive: true,
proxy: {
type: 'jsonp',
url: 'http://localhost/?xx=yy&format=json',
callbackKey: "jsoncallback",
reader: {
type: 'json',
rootProperty: 'GetFolderListing',
record: 'folder'
}
}
}
});
Right now all i get is an error
Uncaught TypeError: Cannot read property 'id' of undefined
Could anyone provide insight on how to solve this or debug it better or how to do custom parsing and pass items back to a store?
Thanks
========
Update - in order for the rootProperty to work in the reader, the json had to be a jsonobject rather than a json array e.g.
{
"GetFolderListing": [
{
"folder": {
"total": 0,
"id": "Contacts",
"name": "Contacts",
"unread": 0,
"leaf": "true"
}
},
{
"folder": {
"total": 0,
"id": "Conversation Action Settings",
"name": "Conversation Action Settings",
"unread": 0,
"leaf": "true"
}
},
.......
Your JSON looks like an array. The error message means that the code tries to access a property of a undefined variable or property.
My first guess would be that the reader is not properly configured for that array type JSON format.

dojo how to get all tree node of specific type?

I wrote the following code to create a dojo tree.
store = new dojo.data.ItemFileWriteStore({url: link});
treeModel = new dijit.tree.TreeStoreModel({
store: store,
query: {
"type": "ROOT"
},
rootId: "newRoot",
childrenAttrs: ["children"]
});
tree= new dijit.Tree({model: treeModel},"treeOne");
Following is my JSON file structure :
{
identifier: "id",
label: "name",
items: [
{id: "ROOT",name: "Change Windows",type: "ROOT"},
]}
I want to get all the nodes (basically their 'id' part)of specific 'type',lets say type= "ROOT". Is there anyway to get all those node? I thought of doing this using tree._itemNodeMap, but don't know any way to iterate through this whole item map,because it need a id as a input to return any specific node.
If you're talking about obtaining the data items programatically, you can get them straight from the store using fetch.
Sample JSON for ItemFile*Store:
{
"identifier": "id",
"label": "name",
"items": [{
"id": "ROOT",
"name": "Root",
"type": "ROOT",
"children": [{
"id": "P1",
"name": "StackExchange",
"type": "website",
"children": [{
"id": "C1",
"name": "StackOverflow",
"type": "website"
},
{
"id": "C2",
"name": "ServerFault",
"type": "website"
}]
},
{
"id": "P2",
"name": "Sandwich",
"type": "food",
"children": [{
"id": "C3",
"name": "Ham",
"type": "food"
},
{
"id": "C4",
"name": "Cheese",
"type": "food"
}]
},
{
"id": "P3",
"name": "Potluck",
"type": "mixed",
"children": [{
"id": "C5",
"name": "Google",
"type": "website"
},
{
"id": "C6",
"name": "Banana",
"type": "food"
}]
}]
}]
}
Sample code:
dojo.require('dojo.data.ItemFileReadStore');
dojo.ready(function() {
var store = new dojo.data.ItemFileReadStore({
url: 'so-data.json'
});
store.fetch({
query: {
type: 'food'
},
queryOptions: {
deep: true
},
onItem: function(item) {
console.log(store.getLabel(item));
}
});
});
This will log Sandwich, Ham, Cheese, and Banana.