Mapping a backbone.collection to a specific property - backbone.js

I'm trying to build a basic structure with backbone.js. My issue is that the server will not directly return an array of objects in json format, but an object which has the the desired array of objects embeded inside:
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": [{...},{...} {...}]}
In this case what I really want in my collection is the "objects" property. So when I try to build a backbone collection, I'm not sure if I should iterate and add them manually or there is someway I can map it directly to the objects property of the object.
Hope thats understandable... thanks!

Use the collection.parse(response) function:
parse is called by Backbone whenever a collection's models are
returned by the server, in fetch. The function is passed the raw
response object, and should return the array of model attributes to be
added to the collection. The default implementation is a no-op, simply
passing through the JSON response. Override this if you need to work
with a preexisting API, or better namespace your responses.

Related

How to Restangularize items in collection off parent object

I am returning an object using Restangular over AngularJS (GPT object is the parent object being returned), with an array being returned corresponding to the projects withing the GPT.
I can do all the Restangular "stuff" like save() etc. on the parent GPT object. However, when I get a reference to individual items in the "projects" collection, I am unable to do a Restangular save() on it. How do I make sure all items returned in the collections below the main object are "Restangularised" so I can perform restful operations on them? i.e. I guess I want a "deep Restangularisation" if that makes sense ;-)...if not, how do I Restangularize an instance just before I attempt to do a save() operation and provide the relevant URL for the PUT/POST etc.
Hope this makes sense.
Regards
i
There is a Restangular.restangularizeElement method.
You can use it as follows (for collection):
Restangular.one('courses', 123).get().then(function (course) {
course.students = Restangular.restangularizeCollection(course, course.students, 'students');
// You should now be able to do 'course.students[0].remove()'
// And if you want to chain promises:
return course;
});
source

Backbone.js: Natively passing attributes to models when fetched with a collection

Let say you are defining a Backbone.js Model. From the documentation we have ...
new Model([attributes], [options])
This seems great for passing some default attributes to a model. When passed the model automatically inherits those attributes and their respective values. Nothing to do. Awesome!
On they other hand lets say we have a Collection of that model.
new Backbone.Collection([models], [options])
Okay, cool we can pass some initial models and some options. But, I have no initial models and no options I need to pass so let's continue. I am going to fetch the models from the server.
collection.fetch([options])
Well I don't have any options, but I want to pass some attributes to add to each models as it is fetched. I could do this by passing them as options and then adding them to the attributes hash in the initialize for the model, but this seems messy.
Is their a Backbone.js native way to do this?
You can pass the attributes as options to fetch and over-ride the collection's parse method to extend the passed options (attributes) on the response.
The solution would look like the following:
var Collection = Backbone.Collection.extend({
url:'someUrl',
parse:function(resp,options) {
if (options.attributesToAdd) {
for (var i=0;i<resp.length;i++)
_.extend(resp[i],options.attributesToAdd);
}
return resp;
}
});
Then to add attributes when you call fetch on the collection, you can:
var collection = new Collection();
collection.fetch({
attributesToAdd:{foo:'bar',more:'foobar'}
});
You may have to tweak the code a bit to work with your JSON structure, but hopefully this will get you started in the correct direction.

Is there anything similar to "KO.mapping.fromJS" in AngularJS?

I wanted to attach some new calculated property to a complex json object returned from a REST Service. This can be easily achieved through KnockoutJS's Mapping pluggin.
But I have decided to go for AngularJS this time. Is there any modules/pluggins similar to knockout's mapping pluggin ??
my PROBLEM is as shown below:
JSON Returned from server is something like:
{
id:2,
name: 'jhon',
relatives:[
{id:1,name:'linda', score:{A:10,B:33,C:78} },
{id:2,name:'joseph', score:{A:20,B:53,C:68} },
{id:3, name:'keith', score:{A:40,B:83,C:30} }
]
}
in the above json object, I want to attach some calculated property to each objects inside "relatives" collection based on the score each relative has.
Try using
angular.extend($scope, data);
I'm also starting to use Angular, coming from Knockout and Durandal :) Hope this might work for you. The data should be accessible in your view ($scope) directly.
Edit: See this thread.
Basically in angular there is no thing similar to Observable variables.
AngularJS makes observing separately from $scope itself.
To make map from Json in AngularJS you can use angular.fromJson to bind data from Json.
To add fields to your scope you also can use angular.extend.
But anyway adding calculated field is thing that you need to make by yourself, for this purpose you can try to use watch methods: $scope.watch, $scope.watchGroup,
watchCollection.

Difference between attributes and toJSON methods in Backbone

Is always equivalent use one or the other?
These prints in console same things
class Model extends Backbone.Model
defaults:
some: 'thing'
other: 'item'
model = new Model
console.log model.attributes
console.log model.toJSON()
toJSON() is a standard method that the JavaScript JSON serializer looks for when serializing an object.
In the context of Backbone, if you override toJSON in your model you can change the format of values which get sent to the server when saving. For example you could filter out read only fields like time stamps.
attributes is the JavaScript object containing the model data, that's what gets altered when you use model.set(). Except if you don't use set() to alter values, then you bypass all the events and loose some of the benefits of backbone. So only use attributes directly if you know what you're doing.

Sencha Touch 2. Arrays in JsonP

I receive Jsonp like:
Mycallback([['name1', 'id1', 'price1'], ['name2', 'id2', 'price2']]
and want to use it for loading store (throuh Jsonp request all works correctly, but I need to use store.load())
How can I load arrays in my store?
How can I access data in callback function?
create a model with fields name, id, price and set the store's model property as this model that you have defined then sencha internally stores the data as an array

Resources