how to set backbone model idAttribute using nested property - backbone.js

My model is structured like this:
model = {
distance: 12.05,
widget: {
id: 1,
creationDate: '12/01/2012'
}
}
How do I set the idAttribute of the model to be the id on the widget property? Is there a syntax to do this?

How about rearranging/flattening your model to make id a top-level property? Override parse and you won't need to set the idAttribute:
var YourModel = Backbone.Model.extend({
parse: function (response) {
var distance = response.distance;
response = response.widget;
response.distance = distance;
return response;
}
});
Now id will be automatically picked up by Backbone as the id. If you need to persist your data back to your datastore, you'll need to overwrite methods necessary to transform the data back. If possible, it would be a better solution if your model came structured with id already at a top level.

Related

Backbone.js How to make collection only accept one class of model

I am new to backbone.js and I am trying to learn it. In the code below I want my collection called "JokesCollection" to only accept adding models of the class "Joke". How do I do achieve this? When setting "Collection" attribute "model" to a certain model, isn´t the collection supposed to only accept that model class and ensure homogeneity? Don´t seam so. When I assign attribute "model" in the "JokesCollection" class to "Joke" it still accepts adding models of class "Persson" witch is not what I want. I only want it to accept adding models of class "Joke".
Joke = Backbone.Model.extend ({
initialize: function(){
console.log("Joke was created");
},
defaults: {
joke : "",
date : "0",
}
});
JokesCollection = Backbone.Collection.extend({
initialize: function(){
console.log("JokesCollection was created");
},
model: Joke // <=== Isn´t this supposed to ensure that the collection only accepts models of class "Joke"?
});
Person = Backbone.Model.extend ({
initialize: function(){
console.log("Person was created");
},
defaults: {
username: "default",
password: "default",
email: "default"
}
});
var person1 = new Person({username:"masterMind"});
var joke1 = new Joke({joke:"Girls are cute and funny hahahaha"});
jokesCollection = new JokesCollection();
jokesCollection.add(joke1);
jokesCollection.add(person1); // This adds a model of class "Person" to the collection. Witch is not what I want. It is not supposed to work! I want "jokesCollection" to only accept models of class "Joke".
console.log(jokesCollection.length); // length gets increased by 1 after adding "person1" to "jokesCollection". Again, it is no supposed to work from my point of view. I want "jokesCollection" to only accept models of class "Joke".
console.log(jokesCollection);
From official docs:
model collection.model
Override this property to specify the model class that the collection
contains. If defined, you can pass raw attributes objects (and arrays)
to add, create, and reset, and the attributes will be converted into a
model of the proper type.
Looks like will have to re-write add method something like this :
add: function(models, options) {
var modelClass = this.model;
isProperIns = this.models.every.(function(model){
return model instanceof modelClass;
});
if (!isProperIns) {
throw new Error("Some of models has unacceptable type")
}
return this.set(models, _.extend({merge: false}, options, addOptions));
}
The purpose of a Collection's model property is not to limit which models the Collection can accept. Rather, that property defines the Model class which the Collection will use when it needs to create a new Model. For instance,when you pass an object literal of Model attributes (as opposed to an instantiated Model) to JokesCollection.add, or when you fetch models in to a JokesCollection, Backbone will use Joke as the Model to instantiate those new additions to the Collection.
There are two ways to ensure your JokesCollection is only populated with instances of Joke. The first way is to never add Model instances to the JokesCollection directly, and instead either:
A) Bring new Jokes in from the server by calling fetch on a JokesCollection
B) add only "raw" Model attributes to the JokesCollection; don't add instantiated Models
However, if you're concerned about a developer accidentally adding a non-Joke Model to the Collection, your other option (as first suggested by #Evgeniy) is to overwrite your JokesCollection's add method. Unlike #Evgeniy's answer though I would not recommend re-writing Backbone's internals. Instead, I would use a simple overwrite that just calls the base Backbone method if possible:
add: function(models, options) {
if (models instanceof Joke) {
// Use the normal Backbone.Collection add method
return Backbone.Collection.prototype.add.call(this, models, options);
}
var allModelsAreJokes = _(models).all(function(model) {
return model instanceof Joke;
));
if (allModelsAreJokes) {
// Use the normal Backbone.Collection add method
return Backbone.Collection.prototype.add.call(this, models, options);
}
// Handle the case where non-Jokes are passed in; either:
// A) convert whatever was passed in to be a Joke:
// var rawModels = _(models).isArray() ? _(models).invoke('toJSON') : model.toJSON();
// return Backbone.Collection.prototype.add.call(this, rawModels, options);
// B) just don't add anything
}

Backbone, get a Collection by collection ID (not RESTful)

I have a backbone collection where the collection is fetched by a url with an id parameter (not RESTful)
url: '/api/categories/?level=2&id=',
So id might be
&id=2
or
&id=45
How do I go about doing this? I've been reading different posts and some say to override Backbone Sync and others say to just do a fetch but modify the data parameters...
When you construct the Collection, pass the id as parameter (by default, Collection do not have an id property while Model do).
Then, override the url property of the Collection and pass a function:
MyCollection = Backbone.Collection.extend({
initialize : function(models, options) {
this.id = options.id;
},
model : // Your Model class
url: function() {
return '/api/categories/?id=' + this.id;
}
});
// [] is the initial, empty set of models
var coll = new MyCollection([], { id: 45 });
coll.fetch(); // the correct url will be called

Backbone JS Models and Collection URLs

If I have a model named "Book" and a collection named "Library" defined as below:
Book
app.Book = Backbone.Model.extend({
defaults: {
title: 'No title',
author: 'Unknown'
}
});
Library
app.Library = Backbone.Collection.extend({
model: app.Book,
url: '/api/books'
});
When I call BookInstance.save() how does it come up with the URL to use? Does it derive it from the collection?
In Backbone.model there are 2 options: url and urlRoot. What is the purpose and difference between these?
In Backbone.collection, there is a single parameter url. Is this always the GET request for the RESTFUL api?
Basically, there are 3 possibilities to construct a model's url:
If the model object exists in a collection then its url method will return an address composed of the collection.url and model.id: [collection.url]/[id].
If you don't want to use a model inside the collection, then model.urlRoot's value can be used instead of the collection.url fragment, resulting in the following pattern: [urlRoot]/[id].
Finally, if you're NOT planning to persist more that one model of a given type to the server or will be defining URLs for each model upon their creation, you can directly assign a value to model.url.
Collections send only GET requests — to get an array of models' JSON data. For saving, removing, and updating, the individual model's save() (POST/PUT/PATCH) and destroy() (DELETE) methods are used.
Here's the source code of Backbone.Model.url, which should help you:
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
var id = this.get(this.idAttribute);
return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
}
In model
urlRoot is used for the Model.
url is used for the instance of the Model.
So if urlRoot exists
then book.fetch() will fetch the data given id, for example
var Book = Backbone.Model.extend({urlRoot: 'books' });
var book = new Book({id: 1});
book.fetch(); // will get /books/1
var Book = Backbone.Model.extend({});
var book = new Book({url: 'books/1'});
book.fetch(); // will get /books/1
var Books = Backbone.Collection.extend({model: Book});
var books = new Books({ /*....*/ });
books.fetch(); // will get /books/
You can refer the backbone Model urlRoot source code here
I hope it makes sense to you, good luck.

How to initialise nested Backbone.js models

In my Application, I have the following JSON data format:
{
Item: {
property1: '',
...
}
}
Following the solution of this stackoverflow.com answer, I modeled my Backbond.js models the following way:
App.Models.Item = Backbone.Model.extend({
});
App.Models.ItemData = Backbone.Model.extend({
defaults: {
'Item': new App.Models.Item
}
});
I now want to bootstap the data to my App from the Backend system on the page load the following way:
var item = App.Models.ItemData({
{Item:
{property1: 'data'}
}
});
The problem I have now is that item.get('Item') returns a plain JavaScrip object and not a Backbone.Model object, because the defaults are overwritten. How can I create the Backbone.js object while ensuring that item.get('Item') is an App.Models.Item object?
I also have read that if you nest Backbone.Models, you should wirite custom getter methods, so the rest of your app dose not have to know about the internal data structure. If so, what is the right way to implement those setters and getters?
You can override the parse method on your ItemData model. No defaults required. The parse method will initialize an empty model, if one is not passed:
App.Models.ItemData = Backbone.Model.extend({
parse: function(attrs) {
attrs = attrs || {};
if(!(attrs.Item instanceof App.Models.Item))
attrs.Item = new App.Models.Item(attrs.Item);
return attrs;
}
});
And then initialize your ItemData model with the option parse:true:
var item = new App.Models.ItemData({Item:{property1: 'data'}}, {parse:true});

How can we represent deep model hierarchies in Backbone.js

I see there are techniques available to have deep models in Backbone, but how about hierachical collections of a single model?
An obvious example is a category tree. So, we can have a category model which has a few properties, 'name', 'type', 'color', whatever.
Rather than have relational db style parent ids, we're using js so we want the data to be represented as json.
Can backbone be leveraged to support (presumably by augmenting collections) data structures that contain instances of a single model in a tree (such that the models and sub models are all instances of the same model)?
Have a look at Backbone-Relational or supermodel.js.
These projects provide better forms of model nesting than the default implementation.
We just nest Backbone models like:
var MyModel = Backbone.Model.extend({});
var MySubModel = Backbone.Model.extend({});
var model = new MyModel({submodel: new MySubModel({color: 'blue'})});
And we override the toJSON methods:
// nested models! Might just override the internal representation of this...
_.extend(Backbone.Model.prototype, {
// Version of toJSON that traverses nested models
toJSON: function() {
var obj = _.clone(this.attributes);
_.each(_.keys(obj), function(key) {
if(!_.isUndefined(obj[key]) && !_.isNull(obj[key]) && _.isFunction(obj[key].toJSON)) {
obj[key] = obj[key].toJSON();
}
});
return obj;
}
});
_.extend(Backbone.Collection.prototype, {
// Version of toJSON that traverses nested models
toJSON: function() {
return this.map(function(model){ return model.toJSON(); });
}
});
So the JSON representations look correct when we nest models. You'll have to pay attention to the parse method on your model though - when you get back your JSON from the server you're going to have to generate all the submodels and collections there in order for it all to work correctly.

Resources