dynamic json to combobox dojo - javascript

I have a problem with filling a Combobox dynamic with a jsonRest from a cross Origin request.
I found a chance to do it static (I hope this is the right vocabulary), but I don’t figured out how to do it for more than one case.Because this is a little part of a bigger Website with five Comboboxes.
Here's the Code
require([
"dojo/_base/array",
"dojo/store/Memory",
"dojo/store/JsonRest",
"dijit/form/ComboBox",
"dojo/store/Cache",
"dojo/store/Observable",
"dijit/form/Textarea",
"dojo/domReady!"
],
function(array, Memory, JsonRest, ComboBox, Cache, Observable, Textarea){
var myArray = new Array;
var myStore = new Observable (new Cache (new JsonRest ({
target: “URL / target”,
idProperty: "WA",
headers: { "X-Requested-With": "" }
}), new Memory ()));
var myTextarea = new Textarea ({
name: "myarea",
style: "width:200px;"
}, "myarea");
myStore.query().then(function(response){
});
store = new Memory({data: myArray}); //Store anlegen ... mit Array befüllen
var comboBoxWA = new ComboBox({
id: "comboWA",
name: "WA",
value: "",
store: store, // übergabe angelegter Store zu Combobox
searchAttr: "WA"
}, "comboWA");
// Array befüllen,.. Store anlegen,... Array dem Store zuweisen
myStore.query().then(function(response){
dojo.forEach( response, function( obj ) {
for (var p in obj) {
if(p=="WA"){
//Here is my Problem, I can’t change the “WA” in myArray.push to some global Variable.
myArray.push({"WA" : obj[p]}); //Array befüllen
console.debug(myArray.toSource());
}}
});
});
});
The json response looks like this
[Object { WA=‘'WA_30_14"}, Object { WA="WA_30_12"} , Object { WA="WA_30_10"}, Object { WA="WA_30_16"},…]
Have anybody an Idea or a simple example for me?
Thanks, Georg

You can also try the below method. so you require "myArray.push({"WA" : obj[p]});" to be "myArray.push({some_global_variable: obj[p]});".
do the following.
1.create an empty LOCAL object before the push method
2.Use the array syntax for assiging the property to the local variable
3.Pass the local variable as parameter to the push method.
var localobj = {}; // step 1
localobj[global_var] = obj[p]; //step 2
myArray.push(localobj); // step 3
You can check the value of the global variable before using push() using
console.log("My glogbal varible"+global_var);

Related

Accessing child objects in JavaScript

'tI am extending two JavaScript objects where one is a variable ajaxed in from a file and the other is a simple object with user preferences.
// local prefs
var prefs = { name: "Bob Barker", show: "Price is Right" };
// ajax in default prefs with dataType: "script"
var defaultPrefs = {
studio: { name: "CBS", location: "Hollywood, CA" },
producers: [ { name: "Producer1" }, { name: "Producer2" } ]
}
// merge prefs
var mergedPrefs = $.extend( prefs, defaultPrefs );
The problem is I can't access the producers or studio using prefs.producers or prefs.studio as they are Objects in the merged file. How can I get around this?
Try this:
var mergedPrefs = $.extend({}, prefs, defaultPrefs);
Extending an empty object will create a new copy of the original object(s).
You can also use Object.assign for the same task, however jQuery.extend also has a deep option to merge recursively whereas Object.assign is always flat (for better performance).
Try this code, but I recomend Object.assign in ES6 to don't use JQuery. Is the same:
var mergedPrefs = Object.assign({}, prefs, defaultPrefs);
Snippet with your code working without Object.assign (using $.extend):
// local prefs
var prefs = {
name: "Bob Barker",
show: "Price is Right"
};
// ajax in default prefs with dataType: "script"
var defaultPrefs = {
studio: {
name: "CBS",
location: "Hollywood, CA"
},
producers: [{
name: "Producer1"
}, {
name: "Producer2"
}]
}
// merge prefs
var mergedPrefs = $.extend({}, prefs, defaultPrefs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Populate Backbone.js JSON response into nested collections inside nested collections/models

My problem is that I am just starting out with Backbone.js and are having trouble wrapping my head around a complex problem. I want to save a form that have infinite fields, and some of the fields also needs to have infinite options. I'm just worried I might have started at the wrong end with a JSON response, instead of building the models/collections first. Here is a short pseudocode of what I try to achieve.
id:
parent: <blockid>
fields: array(
id:
title:
helpertext
options: array(
id:
type:
value:
)
)
Currently I am working with a faked JSON response from the server, which I built from scratch, and now I want to divide it into models and collections on the client side.
//Fake a server response
var JSONresponse = {
"formid":"1",
"fields":[
{
"fieldid":"1",
"title":"Empty title",
"helper":"Helper text",
"type":"radio",
"options":[
{
"optionid":"1",
"value":"Empty option.."
},
{
"optionid":"2",
"value":"Empty option.."
}
]
},
{
// fieldid2
}
]
};
The idea is to add fields as I see fit, and then if the field type is radio/checkbox/ul/ol there must also be an "options" array within the field.
My work so far:
var app = {};
app.Models = {};
app.Collections = {};
app.View = {};
app.Models.Option = Backbone.Model.extend({
});
app.Collections.Options = Backbone.Collection.extend({
model: app.Models.Option
});
app.Models.Field = Backbone.Model.extend({
options: new app.Collections.Options()
});
app.Collections.Fields = Backbone.Collection.extend({
model: app.Models.Field
});
app.Models.Form = Backbone.Model.extend({
formid : "1",
fields: new app.Collections.Fields(),
initialize: function() {
}
});
How do I split up my JSON response into all these models and collections?
(Perhaps I should re-evaluate my approach, and go for something like form.fieldList and form.optionList[fieldListId] instead. If so, how would that look like?)
Edit: Here is a little jsfiddle after many fixes, but I still don't really know how to make the inner options list work.
The easiest solution would be using Backbone Relational or Backbone Associations.
The documentation should be enough to help you get started.
If you don't want to use a library you could override the parse function on the Form model.
app.Models.Form = Backbone.Model.extend({
defaults: {
fields: new app.Collections.Fields()
},
parse: function(response, options) {
return {
formid: response.formid,
fields: new app.Collections.Fields(_.map(response.fields, function(field) {
if (field.options) {
field.options = new app.Collections.Options(field.options);
}
return field;
}))
};
}
});
Now if you fetch a form from the server, the response will be parsed into an object graph of models and collections.
form.get('fields') will return an app.Collections.Fields collection. form.get('fields').first().get('options') will return an app.Collections.Options collection, if any options exist.
Also, you could create the form model like this:
var form = new app.Models.Form(JSONresponse, {
parse: true
});
This would result in the same object structure.
It's quite hard to handle the case of nested models and collections right in plain Backbone.
Easiest way of handling this will be something like this:
var Option = Nested.Model.extend({
idAttribute : 'optionid',
defaults : {
optionid : Integer
value : ""
}
});
var Field = Nested.Model.extend({
idAttribute : 'fieldid',
defaults : {
fieldid : Integer,
title : "",
helper : "",
type : "radio",
options : Option.Collection
}
});
var Form = Nested.Model.extend({
idAttribute : 'formid',
defaults : {
formid: Integer,
fields: Field.Collection
});
https://github.com/Volicon/backbone.nestedTypes
And that's it. Yep, you'll get direct access to the attributes as free bonus, just form.fields.first().options.first().value, without that get and set garbage.

Store array Data Object in localStorage using sencha touch

Using sencha touch, I want to store my array list data in localStorage as shown in image.
onStore refresh function as shown in image below
I stored simple data as Like Date, Id, Name in LocalStorage on BookStore refresh function. But could not find the way to store arrayObject directly to localStorage.
I am not sure i understand your question completely..
If you want store javascript object in local Store, you can do it by converting javascript object into string using JSON.stringify() method.
var testString = JSON.stringify(testObj); //Converts testObject to Json string.
localStorage.testString = testString; // Stores testString into local storage.
You can get testString from local storage and convert it into javascript object by
var testObj = JSON.parse(localStorage.testString);
Or you can use
Ext.encode(); // Encodes an Object, Array to String.
Ext.decode(); // Decodes (parses) a JSON string to an object.
you can store full object but if you just want to store subjects then you need to create new model.
define a model for storing subjects or you can store the full object you are getting.
Ext.define('Demo.model.Subjects', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'int' },
{ name: 'Subjects', type: 'auto' }
]
}
});
define a local store
Ext.define('Demo.store.MySubjectLocalStore', {
extend: 'Ext.data.Store',
config: {
storeId: 'mySubjectLocalStore',
model: 'Demo.model.Subjects',
autoLoad: true,
clearOnPageLoad: true,
proxy: {
type: 'localstorage',
id: 'demo-mySubjects-local-store'
}
}
});
to store data in local store
var subjectsLocal = Ext.getStore('mySubjectLocalStore');
//loop to get your subjects array from main Object then add each array to localstore
//loop start
var subjects = //get it from parent object inside loop
var subjectsModel = Ext.create('Demo.model.Subjects', {
Subjects : subjects,
id: //use integer so that you can get by this id when you retrive it
});
subjectsLocal.add(subjectsModel);
//loop End
subjectsLocal.sync();

ExtJS creating record from existing store

I have created an ext store like so:
var store = new Ext.data.JsonStore({
root: 'vars',
fields: [{ name: 'rec_id', mapping: 'rec' }, { name: 'identity', mapping: 'id'}]
});
This works alright when I add data to the store via loadData(); and some json which looks like:
{ vars : {rec: '1', id:'John'} }
My problem is that if I use add(); to get this record into the store I have to first create it as an Ext.data.Record object.
I do this as pointed out here: https://stackoverflow.com/a/7828701/1749630 and it works ok.
The issue I have is that the records are entered with their mapped parameters rather than the ones I set. I.e, 'rec_id' becomes 'rec' and 'identity' becomes 'id'.
What am I doing wrong here?
You need to do the mapping manually, something like this:
var myNewRecord = new store.recordType({
rec_id: vars.rec,
identity: vars.id
});
store.add(myNewRecord);

Foreign key populated with an object

I would like to make a relation between two models User and Task using backbone-relational.
The relation between the two models is the following:
taskModel.creator_id = userModel.id
// TaskModel
var TaskModel = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: Users
}
],
// some code
});
// Task collection
var TaskCollection = Backbone.Collection.extend({
model: TaskModel,
// some code
});
// User Model
var User = Backbone.RelationalModel.extend({
// some code
});
Actually the problem is in the collection.models, please see the attached images:
Please check this jsfiddle: http://jsfiddle.net/2bsE9/5/
var user = new User(),
task = new Task(),
tasks = new Tasks();
task.fetch();
user.fetch();
tasks.fetch();
console.log(user.attributes, task.attributes, tasks.models);
P.S.:
Actually I am using requireJs to get the UserModel, so I cannot include quotes in relatedModel value.
define([
'models/user',
'backbone',
'relationalModel'
], function (User) {
"use strict";
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: User
}
],
});
);
Edit 2:
http://jsfiddle.net/2bsE9/13/
I updated the jsfiddle to reflect the changes I suggested below. As long as you are calling toJSON on your task, what gets to the server is a json object with the creator_id property set to the actual id of the user. The keyDestination here is redundant as the documentation states it is set automatically if you use keySource.
Edit:
https://github.com/PaulUithol/Backbone-relational#keysource
https://github.com/PaulUithol/Backbone-relational#keydestination
https://github.com/PaulUithol/Backbone-relational#includeinjson
The combination of the three above might solve your issue.
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
// The User object can be accessed under the property 'creator'
key: 'creator',
// The User object will be fetched using the value supplied under the property 'creator_id'
keySource: 'creator_id',
// The User object will be serialized to the property 'creator_id'
keyDestination: 'creator_id',
// Only the '_id' property of the User object will be serialized
includeInJSON: Backbone.Model.prototype.idAttribute,
relatedModel: User
}
],
});
The documentation also states that the property specified by keySource or keyDestination should not be used by your code. The property cannot be accessed as an attribute.
Please try this and comment if that fixes your issue.
Btw, here is a nice blog post that uses backbone-relational end to end.
http://antoviaque.org/docs/tutorials/backbone-relational-tutorial/
Edit
Updated jsfiddle
The problem is that Backbone-Relational explicitly deletes the keySource to 'prevent leaky abstractions'. It has a hardcoded call to unset on the attribute, in Backbone-Relational:
// Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'.
if ( this.key !== this.keySource ) {
this.instance.unset( this.keySource, { silent: true } );
}
You will need to overwrite the unset method in your Task model:
var Task = Backbone.RelationalModel.extend({
urlRoot: ' ',
relations: [
{
type: Backbone.HasOne,
key: 'creator',
relatedModel: User,
keySource: 'creator_id'
}
],
unset: function(attr, options) {
if (attr == 'creator_id') {
return false;
}
// Original unset from Backbone.Model:
(options || (options = {})).unset = true;
return this.set(attr, null, options);
},
sync: function (method, model, options) {
options.success({
id: 1,
name: 'barTask',
creator_id: 1
});
}
});
Obvious problems with this approach are that you will need to modify your code if either Backbone changes its Backbone.Model.unset method or Backbone-Relational changes its keySource behavior.

Categories