I am new to backbone.js. I want to create a collection object to retrieve the json object from server - backbone.js

Here is the data I'm getting from server. How do I store this JSON object in my backbone script and display it in a browser? Please help.
How can i built model or nested collection to retrive this data..
I am getting two kind of response from the server depend on query.
1st response:
[
{
"groups": [
{
"groupname": "Group_all",
"group": [
{
"displayname": "facebook",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value4"
},
{
"displayname": "gmai",
"monitortype": "URL",
"responsetimereport": "value5",
"availabilityreport": "value6"
},
{
"displayname": "zoho",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value1"
}
]
}
]
},
{
"monitor": []
}
]
2.Response
[
{
"groups": []
},
{
"monitor": [
{
"displayname": "facebook",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value1"
}
]
}
]
what i have written to achieve this, i am pasting here
studentdb.Monitor = Backbone.Model.extend({
initialize : function(){
this.Displayname = this.get('displayname');
this.Monitortype = this.get('monitortype');
this.Responsetimereport = this.get('responsetimereport');
this.Availabilityreport= this.get('availabilityreport');
}
});
studentdb.Monitors = Backbone.Collection.extend({ model : studentdb.Monitor });
studentdb.Group1 = Backbone.Model.extend({
initialize : function(){
this.Displayname = this.get('displayname');
this.Monitortype = this.get('monitortype');
this.Responsetimereport = this.get('responsetimereport');
this.Availabilityreport= this.get('availabilityreport');
}
});
studentdb.Group1s = Backbone.Collection.extend({ model : studentdb.Group1 });
studentdb.Group_outer = Backbone.Model.extend({
defaults :{Groupname:""},
initialize : function(){
this.outer_group = new studentdb.Group1s(this.get('group'));
this.Groupname = this.get('groupname');
this.outer_group.parent = this;
}
});
studentdb.Group_outers = Backbone.Collection.extend({ model : studentdb.Group_outer });
studentdb.Overall = Backbone.Model.extend({
initialize : function(){
this.group_outer =new studentdb.Group_outers(this.get('groups'));
this.monitors = new studentdb.Monitors(this.get('monitor'));
}
});
studentdb.Final = Backbone.Collection.extend({
url:'https://data.json',
model : studentdb.Overall,
});

Basically, you must populate a collection with your data fetched from server, and then render your view based on a template.
Instead giving you a complete solution, i think you should first read some tutorials about backbone :
http://blog.joelberghoff.com/2012/07/22/backbone-js-tutorial-part-1/
http://backbonetutorials.com/what-is-a-collection/

could you post your collection code?
I'm afraid your json response probably can't be used directly in a backbone collection.
in that JSON, the array contains two members, the first one contains another array which has only one member (which contains groupName, and group( which really should be called groups))
if it is a 'Groups' collection, you will need to use parse.
docs here: http://backbonejs.org/#Collection-parse
it should process your response and return an array of Group model attributes like so:
[
{
"displayname": "facebook",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value4"
},
{
"displayname": "gmai",
"monitortype": "URL",
"responsetimereport": "value5",
"availabilityreport": "value6"
},
{
"displayname": "zoho",
"monitortype": "URL",
"responsetimereport": "value2",
"availabilityreport": "value1"
}
]

Related

Logic App - Refer and map fields on different JSON data sources

I have two JSON data sources:
Source Data 1:
{
"result": [
{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
}
Source Data 2:
{
"result": [
{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
},
{
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
I want to reference "resource_list" and "project_manager" from Source Data 1 to "sys_id" in Source Data 2 and get "email" out from Source Data 2 and then compose a final Output like below:
Output:
[
{
"__metadata":
{
"uri": "ProjectCode"
},
"externalProject": "11216",
"projectCodeAssignment":
[
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user1#mysite.com"
},
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user2#mysite.com"
}
]
}
]
Is this possible to get this done entirely in Logic App without using Function App or anything to perform it rather.
I write a js script for you. For a quick demo, I omitted some data related to __metadata, seems that is some hard code, not so important here. Try Logic below:
Code in JS code action:
var body = workflowContext.trigger.outputs.body
var data1 = body.data1;
var data2 = body.data2;
var result = [];
data1.result.forEach(item =>{
var resultItem = {};
resultItem.externalProject = item.project;
resultItem.projectCodeAssignment =[];
var resourceIds = item.resource_list.split(',');
resourceIds.forEach(id =>{
var user = data2.result.find( ({ sys_id }) => sys_id === id );
resultItem.projectCodeAssignment.push({"externalProjectAssignee": user.email})
});
result.push(resultItem);
})
return result;
Request Body(your 2 data set are named as data1 and data2 here ):
{
"data1": {
"result": [{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
},
"data2": {
"result": [{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
}, {
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
}
Result:

Creating a Backbone.js Model with complex JSON

I have JSON response as follows
{
"results": [
{
"name": "FOO",
"containerName": "Foo",
"accounts": [
{
"id": "10445570_7601",
"shareeAccountInfo": "",
"siteAccountId": "271555",
"siteId": "271555",
"refreshMode": "NORMAL",
"isNetIncl": "true",
"propertyId": null,
"amount": [
"0.0",
"USD"
]
},
{
"id": "1070_20537601",
"shareeAccountInfo": "",
"siteAccountId": "271555",
"siteId": "271555",
"refreshMode": "NORMAL",
"isNetIncl": "true",
"propertyId": null,
"amount": [
"0.0",
"USD"
]
}
]
},
{
"name": "FOO123",
"containerName": "Foo123",
"accounts": [
{
"id": "10445570_20601",
"shareeAccountInfo": "",
"siteAccountId": "271555",
"siteId": "271555",
"refreshMode": "NORMAL",
"isNetIncl": "true",
"propertyId": null,
"amount": [
"0.0",
"USD"
]
},
{
"id": "10445570_37601",
"shareeAccountInfo": "",
"siteAccountId": "271555",
"siteId": "271555",
"refreshMode": "NORMAL",
"isNetIncl": "true",
"propertyId": null,
"amount": [
"0.0",
"USD"
]
}
]
},
{
"name": "FOO83838",
"containerName": "Foo3232",
"accounts": [
{
"id": "1601",
"shareeAccountInfo": "",
"siteAccountId": "271555",
"siteId": "271555",
"refreshMode": "NORMAL",
"isNetIncl": "true",
"propertyId": null,
"amount": [
"0.0",
"USD"
]
}
]
}
]
}
I am having issues creating a Backbone Model from this JSON response.
Should I be using a nested Model? and how should I be creating a collection based of my Model? Instead will it be a good idea to flatten this JSON structure? any ideas?
Your data structure naturally fits a Collection of Models (I'll call the model Group), where each Group contains a collection of Account models. This collection (and optionally its models) should have a reference to the parent Group.
var Account = Backbone.Model.extend({
})
var Accounts = Backbone.Collection.extend({
model: Account,
initialize: function(models, options) {
this.parent = options.parent;
}
});
var Group = Backbone.Model.extend({
initialize: function() {
this.accounts = new Accounts([], { parent: this });
}
});
var Groups = Backbone.Collection.extend({
model: Group,
// Assuming you make requests to `/group` to produce your result JSON
url: 'group',
// Construct models from the `results` attribute of the response
parse: function(response) {
return response.results;
}
});
There are two main implementation choices to make:
Persistence
If individual Accounts can be persisted seperately from the parent container, perhaps using an endpoint like /group/FOO83838/account/1601, the Acccount model can use the default Backbone.Model.save. The Accounts collection should override url to reference the parent URL:
Accounts = Backbone.Collection.extend({
// code from earlier
url: function() {
return this.parent.url() + '/account';
}
});
If accounts can only be saved as part of the overall Group model, you need to do two things:
First, override Account.save to delegate to the parent's save method:
Account = Backbone.Model.extend({
// code from earlier
save: function() {
this.collection.parent.save();
}
});
Second, override the Group.toJSON to include child accounts:
Group = Backbone.Model.extend({
// code from earlier
toJSON: function() {
var json = Backbone.Model.prototype.toJSON.call(this);
json.accounts = this.accounts.toJSON();
return json;
}
});
(In this example I have used the collection's parent reference. If you prefer you could also save a reference to the parent on this model).
Events
You could allow app code to directly listen to Group.accounts events, in which case no code changes are required:
// Example view code
this.listenTo(group.accounts, 'change', this.onAccountChange, this);
Or, if you prefer the extra encapsulation, you can forward child model changes:
Group = Backbone.Model.extend({
// code from earlier
initialize: function() {
this.accounts = new Accounts([], { parent: this });
this.listenTo(this.accounts, 'all', this.onChildEvent, this);
}
onChildEvent: function(eventName, model, options) {
// write logic to whitelist the events and parameters you are interested in
this.trigger('child:' + eventName, model, options);
}
});
// Example view code
this.listenTo(group, 'child:change', this.onAccountChange, this);
You could also look into Backbone extensions like DeepModel (no longer maintained) or Relational. I usually prefer the finer control of a custom implementation.

How to automatically update connected parts of json with angularjs

I have next json structure:
{
"items": [
{"name":"item1"},
{"name":"item2"},
{"name": "item3"}
],
"groups": [{
"name": "group1",
"items": ["item1", "item3"]
},
{
"name": "group2",
"items": ["item2", "item3"]
},
{
"name": "group3",
"items": ["item1", "item2"]
}]
}
As you can see in my groups I have names of the items.
Is there a way in angularjs to automatically update strings in group > items, when the name of the particular item change. (Is there a way to connect particular parts of the json model?)
Thank you.
You can set up a deep $watch for each item in the item array. When the item changes, iterate over the group items, and replace the old name with the new name:
angular.forEach($scope.model.items, function (item) {
$scope.$watch(function () { return item; }, function (newVal, oldVal) {
angular.forEach($scope.model.groups, function (group) {
var items = group.items;
var itemIndex = items.indexOf(oldVal.name);
if (itemIndex >= 0) {
items[itemIndex] = newVal.name;
}
});
}, true);
});
Demo Fiddle

Backbone (Marionette) fetch in a collection returns an empty array (nested models)

I'm working with nested models and collections in Backbone (Marionette).
// Basic unit
Models.User = Backbone.Model.extend({});
Models.Users = Backbone.Collection.extend({ model: Models.User });
// A Group has a collection of Users
Models.Group = Backbone.Model.extend({
initialize: function() {
var users = new Models.Users(this.get("users"));
this.set("users", users);
}
});
Models.Groups = Backbone.Collection.extend({ model: Models.Group });
// An Organization has a collection of Groups
Models.Organization = Backbone.Model.extend({
initialize: function() {
var groups = new Models.Groups(this.get("groups"));
this.set("groups", groups);
}
});
Models.Organizations = Backbone.Collection.extend({
model: Models.Organization,
url: "./data/data.json"
});
My understanding is that this.get will return an array of objects (as determined via the data.json file) and convert it to a Backbone Collection.
The data.json file has the following structure:
[{
"id": "org1",
"groups": [{
"id": "group1",
"users": [
{ "name": "Alice" },
{ "name": "Bob" }
]
},
{
"id": "group2",
"users": [{ "name": "Charlie" }]
}]
},
{
"id": "org2",
"groups": [{
"id": "groupA",
"users": [{ "name": "Eve" }]
},
{
"id": "groupB",
"users": [
{ "name": "Linda" },
{ "name": "Mallory" }
]
}]
}]
I'm trying to populate the top-most collection (an Organization) with the data from data.json.
In index.html, I have:
<script type="text/javascript">
$(document).ready(function() {
MyApp.OrgManager.addInitializer(function() {
var data = new MyApp.Models.Organizations();
data.fetch({
success: function(collection) {
console.log("Success", collection);
}
});
});
MyApp.start();
});
</script>
fetch returns successfully, but the output of my console for the collection is an empty array. What went wrong?
Solved it. Had to make sure that
I was running the page on a local webserver, since jQuery doesn't like null origin XMLHttpRequests, and
I had to _.bindAll a few things so that this had a proper context.

Binding of a Collection nested inside a Model

I have this model structure in my mind:
var app = app || {};
// Caratteristica
app.Attribute = Backbone.Model.extend({
defaults: {
name: '',
selected: false
}
});
app.Attributes = Backbone.Collection.extend({
model: app.Attribute
});
// Tipo Caratteristica
app.AttributeCategory = Backbone.Model.extend({
defaults: {
name: '',
attributes: new app.Attributes()
}
});
app.AttributeCategories = Backbone.Collection.extend({
model: app.AttributeCategory,
url: '/ajax/attributes.cfm'
});
My API in '/ajax/attributes.cfm' will give me a response like that:
[
{
"id": "1",
"name": "Type1",
"attributes": [
{
"id": "1",
"name": "Attribute1"
},
{
"id": "2",
"name": "Attribute2"
},
{
"id": "3",
"name": "Attribute3"
}
]
},
{
"id": "2",
"name": "Type2",
"attributes": [
{
"id": "1234",
"name": "Attribute1234"
},
{
"id": "2567",
"name": "Attribute2567"
}
]
}
]
My question is: will this json data be parsed correctly into my nested data structure?
I mean I want to end up having two app.AttributeCategory items in my app.AttributeCategories collection. Each of these two items must then have its attributes property filled with the corresponding app.Attributes collection.
If the answer was NO, how would I override the parse() function for achieving that result?
I did it like this:
// Tipo Caratteristica
app.AttributeCategory = Backbone.Model.extend({
defaults: {
name: ''
},
initialize: function(options) {
this.set('attributes', new app.Attributes(options.attributes));
Backbone.Model.prototype.apply(this, arguments);
}
});
But better use RationalModel for set up relations betweens models
You can create the collection inside an initialize method in your AttributeCategory model, like this:
app.AttributeCategory = Backbone.Model.extend({
...
initialize: function () {
this.set('attributes', new app.Attributes(this.get('attributes')));
}
});

Resources