creating nested structure with backbone-relational - backbone.js

I'm trying to create a three cascading dropdown lists. First one constains projects, second contains tasks for selected project and the last one sites for selected task.
I want to use the Backbone-Relational plugin, but have hard time to create the proper relations. That's my first time with this plugin.
Code so far:
App.Models.ProjectItem = Backbone.RelationalModel.extend({
default: {
id: 0,
name: ''
},
relations: [{
type: Backbone.HasMany,
key: 'tasks',
relatedModel: App.Models.TaskItem,
//includeInJSON: Backbone.Model.prototype.idAttribute,
collectionType: App.Collections.TasksCollection,
reverseRelation: {
key: 'projectId',
//includeInJSON: Backbone.Model.prototype.idAttribute,
type: Backbone.HasOne
}
}]
});
App.Collections.ProjectsCollection = Backbone.Collection.extend({
model: App.Models.ProjectItem
});
App.Models.TaskItem = Backbone.RelationalModel.extend({
default: {
id: 0,
name: ''
},
relations: [{
type: Backbone.HasMany,
key: 'sites',
relatedModel: App.Models.SiteItem,
includeInJSON: Backbone.Model.prototype.idAttribute,
collectionType: App.Collections.SitesCollection,
reverseRelation: {
key: 'taskId',
//includeInJSON: Backbone.Model.prototype.idAttribute,
type: Backbone.HasOne
}
}]
});
App.Collections.TasksCollection = Backbone.Collection.extend({
model: App.Models.TaskItem
});
App.Models.SiteItem = Backbone.RelationalModel.extend({
default: {
id: 0,
name: ''
}
});
App.Collections.SitesCollection = Backbone.Collection.extend({
model: App.Models.SiteItem
});
Creating single project:
var item = new App.Models.ProjectItem({
id: 1,
name: 'project',
tasks: [
{
id: 1,
name: 'task',
sites: [
{
id: 1,
name: 'site'
}
]
}
]
})
This object serialized to json looks like this:
"{"id":1,"name":"task","tasks":[1],"sites":[{"id":1,"name":"site"}],"projectId":null}"
My questions:
1) Why the sites array is not nested in the tasks one?
2) Sites collection is not serialized the same way that tasks one is. Should I create a relations in the site model too?
3) Why the projectId is returned for the root?

After many hours of trials and errors I finally got it. The order matters..
Working code:
App.Models.SiteItem = Backbone.RelationalModel.extend({
default: {
siteId: 0,
name: ''
}
});
App.Collections.SitesCollection = Backbone.Collection.extend({
model: App.Models.SiteItem
});
App.Models.TaskItem = Backbone.RelationalModel.extend({
default: {
taskId: 0,
name: ''
},
relations: [{
type: Backbone.HasMany,
key: 'sites',
relatedModel: App.Models.SiteItem,
//includeInJSON: Backbone.Model.prototype.idAttribute,
collectionType: App.Collections.SitesCollection,
reverseRelation: {
key: 'task',
includeInJSON: 'taskId',
type: Backbone.HasOne
}
}]
});
App.Collections.TasksCollection = Backbone.Collection.extend({
model: App.Models.TaskItem
});
App.Models.ProjectItem = Backbone.RelationalModel.extend({
default: {
projectId: 0,
name: ''
},
relations: [{
type: Backbone.HasMany,
key: 'tasks',
relatedModel: App.Models.TaskItem,
// includeInJSON: 'taskId',
collectionType: App.Collections.TasksCollection,
reverseRelation: {
key: 'project',
includeInJSON: 'projectId',
type: Backbone.HasOne
}
}]
});
App.Collections.ProjectsCollection = Backbone.Collection.extend({
model: App.Models.ProjectItem
});
For sample data:
var item = new App.Models.ProjectItem({
projectId: 2,
name: 'first',
tasks: [
{
taskId: 1,
name: 'task',
sites:[{siteId:1, name: 'site'}]
}
]
});
I got this json string:
"{"projectId":2,"name":"first","tasks":[{"taskId":1,"name":"task","sites":[{"siteId":1,"name":"site","task":1}],"project":2}]}"

Related

unexpected token ",", expected expression in sanity studio vision

I am following a course on react native and We are using Sanity as our backend. I have already set the schemas and made the adjustments in my Sanity Studio.
HERE IS MY FEATURED SCHEMA CODE:
export default {
name: 'featured',
title: 'featured Menu Categories',
type: 'document',
fields: [
{
name: 'name',
type: 'string',
title: 'Featured category name',
validation: (Role) => Role.required(),
},
{
name: 'short_description',
type: 'string',
title: 'Short description',
validation: (Role) => Role.max(200),
},
{
name: 'restuarants',
type: 'array',
title: 'Restuarants',
of: [{ type: 'reference', to: [{ type: 'restuarant' }] }],
},
],
};
HERE IS MY RESTAURANT SCHEMA CODE:
export default {
name: 'restaurant',
title: 'Restuarant',
type: 'document',
fields: [
{
name: 'name',
type: 'string',
title: 'Restuarant name',
validation: (Role) => Role.required(),
},
{
name: 'short_description',
type: 'string',
title: 'Short description',
validation: (Role) => Role.max(200),
},
{
name: 'image',
type: 'image',
title: 'Image of the Restuarant',
},
{
name: 'lat',
type: 'number',
title: 'latitude of the restaurant',
},
{
name: 'long',
type: 'number',
title: 'longitude of the restaurant,
},
{
name: 'address',
type: 'string',
title: 'Address of the Restuarant',
validation: (Role) => Role.required(),
},
{
name: 'rating',
type: 'number',
title: 'Enter a rating of (1 - 5)',
validation: (Role) =>
Role.required()
.min(1)
.max(5)
.error('please enter a number between 1 - 5'),
},
{
name: 'type',
type: 'string',
title: 'Category',
validation: (Role) => Role.required(),
type: 'reference',
to: [{ type: 'category' }],
},
{
name: 'dishes',
type: 'array',
title: 'Dishes',
of: [{ type: 'reference', to: [{ type: 'dish' }] }],
},
],
};
I also did one for the dish and category.
Then I went to my Sanity Studio to fill in my restaurant schema fields;
After I went to my Vision Board in Sanity Studio and did a query(Just like the instructor):
*[_type == "featured"]{
...,
restuarants[]=> {
...,
dishes[]=> ,
type=> {
name
}
},
}
And I got an error of:
unexpected token ",", expected expression ;
I did what any developer would have done if they got an error. I double-checked my code and compared it to the instructor in the video. (I still got the error). Then I googled it(And found no answer). It's been 2 days now and I still haven't found anything.
This is my first querying in Sanity and I am not sure what I am doing wrong with my query. Can anyone please help me? Thanks.
As the error mentioned, you missed a ' in your schema code.
Keep a ' after restaurant
{
name: 'long',
type: 'number',
title: 'longitude of the restaurant',
},
No worries I found the answer to my problem. The problem was with my querying.
HERE WAS MY CODE BEFORE:
*[_type == "featured"]{
...,
restuarants[]=> {
...,
dishes[]=> ,
type=> {
name
}
},
}
THIS IS HOW I WAS SUPPOSED TO WRITE IT:
*[_type == "featured"]{
...,
restuarants[]-> {
...,
dishes[] -> ,
type-> {
name
}
},
}
I was supposed to use a straight line instead of an equal sign.
I hope this helps anyone who runs into this problem

Ext Filter with special value

I have a Model A (include Model B). For example:
fields: [{
name: 'code',
type: 'string'
}]
hasMany: [{
name: 'modelB',
model: 'modelB'
}]
Model B:
fields: [{
name: 'code',
type: 'string'
}]
I want to add filter to Store A (mapping with Model A) by Model B's code. For example:
Data: {code: 'A001', modelB: [{code: 'B001'}, {code: 'B002'}]},
{code: 'A002', modelB: [{code: 'B001'}, {code: 'B003'}]},
{code: 'A003', modelB: [{code: 'B002'}]}
Query value: 'B002'
Expected result: 'A001' and 'A003'
I tried:
customFilter = Ext.create('Ext.util.Filter', {
property: 'modelB.code',
operation: '=',
value: '001' // <- Model B's code
});
storeA.addFilter(customFilter);
It's not working. Please help!

Sencha touch 2.4.1 - localstorage using own ID

I am trying to save data to local storage and I want to use my own ID.
But new id is generated.. and not using my ID.
My model:
Ext.define('mOQOLD.model.ActivityList',{
extend:'Ext.data.Model',
config:{
dProperty : 'uniqueid', // dummy name(not a field)
clientIdProperty : 'ID',
identifier: {
type: 'simple'
},
fields: [
{ name: "ID", type: "auto" },
{ name: "activityID", type: "int" },
{ name: "newRandom", type: "float" },
{ name: "rTime", type: "date", dateFormat: "Y-m-d H:i:s" }
]
}
});
My store:
Ext.define('mOQOLD.store.ActivityListStoreOffline',{
extend:'Ext.data.Store',
requires:["mOQOLD.model.ActivityList",
'Ext.data.proxy.LocalStorage'],
config:{
storeId:"ActivityListStoreOffline",
model:"mOQOLD.model.ActivityList",
grouper: {
groupFn: function(rec) {
var date = rec.get("actDtlStime");
return Ext.Date.format(date, "h a");
}
},
autoLoad:false,
sorters: [
{ property: "actDtlStime", direction: "ASC" }
],
proxy : {
type : 'localstorage',
id : "ActivityListStoreOffline",
model : "mOQOLD.model.ActivityList",
reader: {
type: "json"
}
}
}
})
The result( chrome) :
key : ActivityListStoreOffline-ext-record-19
value:
{"ID":"153",15:13:00","activityID":111,"newRandom":null,"rTime":"2015-05-26 19:31:51","id":"ext-record-19"}
What I expect:
key : ActivityListStoreOffline-153
value:
{"ID":"153",15:13:00","activityID":111,"newRandom":null,"rTime":"2015-05-26 19:31:51"} no id generated!!!
Thanks in advance..
There are two places you can set the ID:
In the model(http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.data.Model-cfg-idProperty)
and in the reader (http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.data.reader.Reader-cfg-idProperty)
Both places use the "idProperty" attribute. Which defaults to lowercase 'id'.
For example, change your reader to:
proxy : {
type : 'localstorage',
id : "ActivityListStoreOffline",
model : "mOQOLD.model.ActivityList",
reader: {
type: "json",
idProperty: "ID",
}
}

Extjs localstore method set

I am not able to update record in localStorage by id. I get the exception :
Uncaught TypeError: Cannot read property 'type' of undefined WebStorage.js:391Ext.define.getIds WebStorage.js:391Ext.define.update WebStorage.js:190Ext.define.runOperation Batch.js?_dc=1423751003307:251Ext.define.start Batch.js?_dc=1423751003307:178Ext.define.batch Proxy.js?_dc=1423751002203:456Ext.define.sync AbstractStore.js?_dc=1423751002173:810Ext.define.afterEdit AbstractStore.js?_dc=1423751002173:906Ext.define.callStore Model.js?_dc=1423751003310:1814Ext.define.afterEdit Model.js?_dc=1423751003310:1773Ext.define.set Model.js?_dc=1423751003310:1175(anonymous function) Main.js?_dc=1423751002786:26(anonymous function) VM3763:6wrap
My model is simple:
Ext.define('AM.model.Points', {
extend: 'Ext.data.Model',
idProperty: {
name: 'UUID',
type: String,
isUnique: true
},
fields: [
{
name: 'NO',
type: "string"
},
{
name: 'Y',
type: "int"
},
{
name: 'ROW',
type: 'int'
},
{
name: 'SEAT',
type: 'string'
},
{
name: 'PROCEEDED',
type: 'int'
},
{
name: 'X',
type: "int"
},
{
name: "CurrentPlace",
type: "int",
defaultValue: 0
}
],
});
My controller class init function:
init: function(){
// метод getStore контроллера возвращает экземпляр хранилища,
// если он уже создан - или создаёт его
console.log('Main controller init function()');
var changingImage = Ext.create('Ext.Img', {
src: '/is-bin/intershop.static/WFS/EnterpriseOrg-MainChannel-Site/ProductStore/ru_RU/kzch.jpg',
renderTo: Ext.get('canv1')
});
Ext.get('canv1').on('click', function(eventObj, elRef) {
var index = Ext.StoreMgr.lookup("LocalStore").findExact('UUID',AM.util.Utilities.CurrentPlace);
var rec = Ext.StoreMgr.lookup("LocalStore").getAt(index);
console.log('Ext.StoreMgr.lookup("LocalStore") ' + Ext.StoreMgr.lookup("LocalStore"));
console.log('index' + index);
console.log('rec' + rec);
var uuid = rec.get('UUID');
console.log('uuid is: '+uuid);
**rec.set('X', window.event.offsetX);**
});
The logic is that I click on canvas and pass X coordinate of the click to method on click. I retrieve model from store by previously saved id to update it. But I cant update record. What should be done? Version 4.2.1 Thanx in advance.

Data model : Association getter returns undefined

My problem consists of not being able to retrieve data through associations.
After running setup() from console i would expect firstTurbine.getPlant() to return the associated plant, yet it returns undefined.
I've spent alot of time looking for a solution I'm probably not looking the right place.
Relevant code is attached below:
Ext.regApplication({
name: "app",
launch: function() {
//app.views.viewport = new app.views.Viewport();
}
});
app.models.Plant = Ext.regModel("Plant", {
fields: [
{name: "id", type: "int"},
{name: "name", type: "string"},
{name: "notes", type: "auto"}
],
proxy: {type: 'localstorage', id:'plantStorage'}
});
app.models.Turbine = Ext.regModel("Turbine", {
fields: [
{name: "id", type: "int"},
{name: "plant_id", type: "int"},
{name: "name", type: "string"},
{name: "notes", type: "auto"}
],
proxy: {type: 'localstorage', id:'turbineStorage'},
belongsTo: 'Plant'
});
app.stores.plants = new Ext.data.Store({
model: "Plant",
autoLoad: true,
data : [
{id: 1, name: 'Plant1', notes: ["Note1", "Note2"]},
{id: 2, name: 'Plant2', notes: ["Note1", "Note2"]},
{id: 3, name: 'Plant3', notes: ["Note1", "Note2"]}
]
});
app.stores.turbines = new Ext.data.Store({
model: "Turbine",
autoLoad: true,
data: [
{id: 11, "plant_id": 1, name: "T41", notes: ["Turbine note 1", "Turbine note 2"]},
{id: 12, "plant_id": 1, name: "T13", notes: ["Turbine note 1", "Turbine note 2"]}
]
});
function setup(){
firstPlant = app.stores.plants.getAt(0);
if(!firstPlant){
firstPlant = Ext.ModelMgr.create({name:"TestPlant1", id: 1}, "Plant");
app.stores.plants.add(firstPlant);
app.stores.plants.sync();
}
firstTurbine = app.stores.turbines.getAt(0);
if(!firstTurbine){
firstTurbine = Ext.ModelMgr.create({name:"T31", id: 30, plant_id: 1}, "Turbine");
app.stores.turbines.add(firstTurbine);
app.stores.turbines.sync();
}
return {firstTurbine: firstTurbine, firstPlant: firstPlant};
}
The getter function created by the belongsTo association takes a callback function as argument. The callback function will have the related object as its first argument.
turbine.getPlant(function(Plant){
console.log(Plant);
});
I will attach a full working example since this have cost me alot of headache and might have aswell for others.
first the json data:
{
"plants": [{
"id": 1,
"name": "Plant1",
"notes": ["Note1", "Note2"]
}],
"turbines": [
{
"id": 11,
"plant_id": 1,
"name": "T41",
"notes": ["Turbine note 1", "Turbine note 2"]
}]
}
And the javascript:
Ext.regApplication({
name: "app",
launch: function() {}
});
app.models.Plant = Ext.regModel("Plant", {
fields: ["id", "name", "notes"],
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
root: 'plants'
}
}
});
app.models.Turbine = Ext.regModel("Turbine", {
fields: ["id", "plant_id", "name", "notes"],
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
root: 'turbines'
}
},
belongsTo: 'Plant'
});
app.stores.plants = new Ext.data.Store({
model: "Plant"
});
app.stores.turbines = new Ext.data.Store({
model: "Turbine",
autoLoad: {
callback: function(records) {
var turbine = records[0];
turbine.getPlant(function(Plant){
console.log(Plant);
});
}
}
});

Resources