backbone fetch complicate structure - javascript

I have 3 models on backbone:
var Level1Model = Backbone.Model.extend({
defaults: {
level2Collection: null
}
});
var Level2Model = Backbone.Model.extend({
defaults: {
level3Collection: null,
text: null
}
});
var Level3Model = Backbone.Model.extend({
defaults: {
text: null
}
});
I have two REST services (urls):
1. One that gets Level1Model id and returns Level1Model with Level2Model and id's of Level3.
For example:
{
Level2Collection: [
{
text: "aaa",
Level3Collection: [ {id:1}, {id:2}, {id:3} ]
},
{
text: "bbb",
Level3Collection: [ {id:4}, {id:5} ]
}
]
}
2. One that gets Level3Model id and returns Level3Model data.
I am looking a way to fetch all the data structure by doing:
var level1Ins = new Level1Model({id:123});
level1Ins.fetch({
success: function() {
doSomething();
}
});
I am really confused of how to do it. For example, I don't know how can I fill the Level3Collection and also call doSomething() when success loading all elements.
How can I load the entire level1 instance?

You should try Backbone Relational. It makes this kind of thing very easy to work with.

Related

Update model with data retrieved from backbone.sync call

I have a backbone model similar to this.
User = Backbone.Model.extend({
defaults: {
id: null,
name: '',
groups: []
},
addGroup: function(group) {
return this.sync(
'update',
this,
{url: this.url() + 'add_group', data: 'group=' + group}
);
}
}
UserCollection = Backbone.Collection.extends({
model: User,
url: '/api/users'
});
The purpose behind this call is that adding the permission triggers all sorts of backend checks and other changes. The actual code, which I'm trying to not to expose here, demonstrates the need better.
The /api/users/add_group endpoint returns a new representation of the Users model, which I wish to have applied to the model with all of the appropriate events triggered. The best work-around I could find is this.
User = Backbone.Model.extend({
defaults: {
id: null,
name: '',
groups: []
},
addGroup: function(group) {
model = this;
return this.sync(
'update',
this,
{
url: this.url() + 'add_group',
data: 'group=' + group,
success: function() {model.fetch();}
}
);
}
}
However, it feels like there is probably a better solution where I can call arbitrary endpoints and have the model updated with the returned data.

Ember data EmbeddedRecordMixin

I've been trying to make an embedded list of models get loaded. I understood from the demo that EmbeddedRecordsMixin was the way to go but this still fails with: "Error: Assertion Failed: TypeError: factory is undefined" I have tried to separate them in my fixtures and this works just fine so I must be missing something in the embedding part even though it follows this: http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
Does this doesn't work with Fixtures then?
var App = window.App = Ember.Application.create({
LOG_TRANSITIONS: true
});
var attr = DS.attr;
App.Modificators = DS.Model.extend({
"tpe": attr('string')
});
App.SpecialStuff = DS.Model.extend({
"title": attr('string'),
"body": attr('string'),
"modificators": DS.hasMany('modificators')
});
App.SpecialStuffSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
"modificators": { embedded: 'always' }
}
});
App.SpecialStuff.reopenClass({
FIXTURES: [{
"id": 79,
"title": "fewfew",
"body": "kkk",
"modificators": [{
"id": 1,
"tpe": "vv",
},
{
"id": 2,
"tpe": "mv",
}]
}]
});
App.SpecialStuffIndexRoute = Ember.Route.extend({
model: function (params) {
return this.store.find('special_stuff');
}
});
App.Router.map(function () {
// Add your routes here
this.resource('specialStuff', function() {});
});
Ember.Inflector.inflector.uncountable('modificators');
Ember.Inflector.inflector.uncountable('special_stuff');
App.ApplicationAdapter = DS.FixtureAdapter.extend({});
Ember Data's Fixture Adapter doesn't use a serializer for fetching data. You're better off mocking json calls with something like https://github.com/jakerella/jquery-mockjax and using the rest adapter.
Here's some examples: Ember-data embedded records current state?

best way to realize backbone list application

I use backbone.boilerplate for creating a simple application.
I want to create module that can show collections of sites. Each sites has id and title attributes (example [{ id: 1, title: "github.com" }, { id: 2, title: "facebook.com" }].
My router:
routes: {
"": "index",
"sites": "sites"
},
sites: function () {
require(['modules/sites'], function (Sites) {
var layout = new Sites.Views.Layout();
app.layout.setView('#content', layout);
});
}
So, my sites module has layout, which do this:
Sites.Views.Layout = Backbone.Layout.extend({
template: "sites/layout",
className: 'container-fluid',
initialize: function () {
_.bindAll(this);
this.collection = new Sites.Collections.Sites();
this.collection.fetch({
success: this.render
});
},
beforeRender: function () {
var siteList = new Sites.Views.SiteList({
collection: this.collection
});
this.setView('.content', siteList);
},
});
Sites.Views.SiteList = Backbone.View.extend({
template: 'sites/list',
beforeRender: function () {
this.collection.each(function (model) {
var view = new Sites.Views.SiteItem({
model: model
});
this.insertView('tbody', view);
}, this);
}
});
Sites.Views.SiteItem = Backbone.View.extend({
template: 'sites/item',
tagName: 'tr',
serialize: function () {
return {
title: this.model.get('title')
};
}
});
ok. and now my question: help me please to choose best way to render one site view when user click on element of collection. I want that it is works like gmail: one screen for all letters and all screen for one letter when it choosed. Maybe you have link with example of similar application. I am waiting for your advices.
Looking at your pastebin code it seems like you have a basic understanding of Backbone, which is certainly all you need to get started.
That being said, you might find this article/tutorial helpful. It walks through the process of building inter-connected views (in the tutorial they are related <select> elements) which use AJAX to update their values:
http://blog.shinetech.com/2011/07/25/cascading-select-boxes-with-backbone-js/

Javascript this not referring to current object in backbone model

I have a tree-like backbone model, something like:
var Leaf = Backbone.Model.extend({
urlRoot: "tests.json",
initialize: function() {
if (Array.isArray(this.get('children'))) {
var childTree = new Tree();
childTree.on("add",this.addChild);
childTree.add(this.get('children'));
this.set({children: childTree});
}
},
addChild : function(child){
console.log(this);console.log(child);
},
});
var Tree = Backbone.Collection.extend({
model: Leaf,
url: "tests.json",
});
addChild is called for each element added to childTree in the initialization method.
But inside the addChild method, this refers to the childTree collection instead of the model... I'm relatively unexperienced with javascript, and it doesn't make sense to me at all... Is this correct behavior, and how can I bind the listener to the model inside addChild ?
The JSON is something like:
[{
"name":"root",
"children":[
{
"name":"inner",
"children":[{
"name":"innerinner",
"attr":{"class":""},
"checked":true,
"locked":true,
"children":[]
}]
}]
}]
Thanks in advance!
try
childTree.on("add", _.bind(this.addChild, this));

Backbone-Relational related models not being created

I'm trying to create a nested, relational backbone project but I'm really struggling. The rough idea of what I'm trying to do is shown below but I was under the impression upon calling fetch() on Client, a number of bookings would automatically be created based on the bookings being returned as JSON.
The format of my JSON can be seen beneath the outline of the MVC:
/****************************************************
/* CLIENT MODEL - Logically the top of the tree
/* has a BookingsCollection containing numerous Booking(s)
/* Client
/* -Bookings [BookingsCollection]
/* -Booking [Booking]
/* -Booking [Booking]
/*****************************************************/
var Client = Backbone.RelationalModel.extend({
urlRoot: '/URL-THAT-RETURNS-JSON/',
relations: [
{
type: Backbone.HasMany,
key: 'Booking',
relatedModel: 'Booking',
collectionType: 'BookingsCollection'
}
],
parse: function (response) {
},
initialize: function (options) {
console.log(this, 'Initialized');
}
});
var Booking = Backbone.RelationalModel.extend({
initialize: function (options) {
console.log(this, 'Initialized');
}
});
var BookingsCollection = Backbone.Collection.extend({
model: Booking
});
Any help outlining what I'm doing wrong would be massively appreciated.
Thanks
EDIT
Thanks for taking the time to post the feedback, it's exactly what I was hoping for.
Is it the case that the JSON physically defines the actual attributes of models if you don't go to the effort of setting attributes manually?
In other words, if the JSON I get back is as you have suggested above, would Backbone simply create a Client object (with the 4 attributes id, title, firstname & surname) as well as 2 Booking objects (each with 4 attributes and presumably each members of the BookingsCollection)?
If this is the case, what is the format for referencing the attributes of each object? When I set up a non-backbone-relational mini-app, I ended up in a situation whereby I could just reference the attributes using Client.Attribute or Booking[0].EventDate for example. I don't seem to be able to do this with the format you have outlined above.
Thanks again.
The JSON being returned is not what Backbone or Backbone-Relational is expecting by default.
The expectation of Backbone and Backbone-Relational is:
{
"id": "123456",
"Title":"Mr",
"FirstName":"Joe",
"Surname":"Bloggs",
"Bookings": [
{
"id": "585462542",
"EventName": "Bla",
"Location":"Dee Bla",
"EventDate":"November 1, 2012"
},
{
"id": "585462543",
"EventName": "Bla",
"Location":"Dee Bla",
"EventDate":"November 1, 2012"
}
]
}
To use your response, you need to create a parse function on the Client model that returns the structure I've posted above.
A jsFiddle example of your model definitions working with my example JSON: http://jsfiddle.net/edwardmsmith/jVJHq/4/
Other notes
Backbone expects ID fields to be named "id" by default. To use another field as the ID for a model, use Model.idAttribute
The "key" for the Bookings Collection I changed to "Bookings"
Sample Code:
Client = Backbone.RelationalModel.extend({
urlRoot: '/URL-THAT-RETURNS-JSON/',
relations: [
{
type: Backbone.HasMany,
key: 'Bookings',
relatedModel: 'Booking',
collectionType: 'BookingsCollection'
}
],
parse: function (response) {
},
initialize: function (options) {
console.log(this, 'Initialized');
}
});
Booking = Backbone.RelationalModel.extend({
initialize: function (options) {
console.log(this, 'Initialized');
}
});
BookingsCollection = Backbone.Collection.extend({
model: Booking
});
myClient = new Client( {
"id": "123456",
"Title":"Mr",
"FirstName":"Joe",
"Surname":"Bloggs",
"Bookings": [
{
"id": "585462542",
"EventName": "Bla",
"Location":"Dee Bla",
"EventDate":"November 1, 2012"
},
{
"id": "585462543",
"EventName": "Bla",
"Location":"Dee Bla",
"EventDate":"November 1, 2012"
}
]
});
console.log(myClient);​
Post Edit
Yes, the JSON pretty much defines the attributes of the model. You can use a combination of parse(), defaults, and validate() to better control what attributes are valid and allowed.
The canonical way of reading and setting properties on a Backbone Model is through the get(), escape(), and set() functions.
set is especially important as this does a bunch of housekeeping, such as validating the attribute and value against your validate function (if any), and triggering change events for the model that your views would be listening for.
In the specific case of the situation in this answer, you might
myClient.get('Title'); // => "Mr"
myClient.get('Bookings'); //=> an instance of a BookingsCollection with 2 models.
myClient.get('Bookings').first().get('Location'); //=> "Dee Bla"
myClient.get('Bookings').last().get('Location'); //=> "Dee Bla"
myClient.get('Bookings').first().set({location:"Bora Bora"});
myClient.get('Bookings').first().get('Location'); //=> "Bora Bora"
myClient.get('Bookings').last().get('Location'); //=> "Dee Bla"

Categories

Resources