I'm using backbone.js and backbone relational 0.5.0 with a Rails 3.2 backend. I have a Card model which has_many Notes.
Here are my JS models and collections:
Workflow.Collections.Cards = Backbone.Collection.extend({
model: Workflow.Models.Card,
url: '/cards'
});
Workflow.Models.Card = Backbone.RelationalModel.extend({
modelName : 'card',
urlRoot : '/cards',
relations: [
{
type: Backbone.HasMany,
key: 'notes',
relatedModel: 'Workflow.Models.Note',
collectionType: 'Workflow.Collections.Notes',
includeInJSON: false,
reverseRelation: {
key: 'card',
includeInJSON: 'id'
}
}]
});
Workflow.Collections.Notes = Backbone.Collection.extend({
model: Workflow.Models.Note,
url: '/cards/74/notes' // intentionally hard-coded for now
});
Workflow.Models.Note = Backbone.RelationalModel.extend({
modelName : 'note',
urlRoot : '/notes'
});
Normal fetching works great, but when I try fetchRelated in the console, I get an empty array:
card = new Workflow.Models.Card({id: 74}) // cool
card.fetch() // hits the sever with GET "/cards/74" - works great
card.fetchRelated('notes') // [] - didn't even try to hit the server
What's weird is that this works:
card.get('notes').fetch() // cool - GET "/cards/74/notes"
I could use that method and parse the response text, but it feels really dirty.
Anyone know what I'm missing here?
Thanks in advance, this one is really torturing me!
Stu
You should create Card with Note ids array: card = new Workflow.Models.Card({id: 74, notes: [74, 75]}); and change the url method of Notes accordingly:
Workflow.Collections.Notes = Backbone.Collection.extend({
model: Workflow.Models.Note
});
Workflow.Models.Note = Backbone.RelationalModel.extend({
modelName : 'note',
urlRoot : function () {
return this.get('card').url() + '/notes';
}
});
card = new Workflow.Models.Card({id: 74, notes: [74, 75]});
card.fetchRelated('notes');
http://jsfiddle.net/theotheo/5DAzx/
I should have posted my solution a while back - there might well be a better way, but this is the convention I've gone with:
All of the following code is in the card view (which is where the notes are displayed).
First, I bind a renderNotes method to the 'reset' event on the card's notes collection:
initialize: function () {
_.bindAll(this);
this.model.get('notes').on('reset', this.renderNotes);
var self = this;
this.model.get('notes').on('add', function(addedNote, relatedCollection) {
self.renderNote(addedNote);
});
}
I also bind to the 'add' on that collection to call a singular renderNote.
The renderNotes and renderNote methods work like this:
renderNotes: function () {
if (this.model.get('notes')) {
this.model.get('notes').each(this.renderNote);
}
},
renderNote: function (note) {
var noteView = new Workflow.Views.Note({ model: note });
this.$('.notes').append(noteView.render().el);
},
Then, the last piece of the puzzle is to actually hit the server up for the card's notes (which will in turn fire the 'reset' event I bound to above). I do this in the card view's render method:
render: function () {
// render all of the eager-loaded things
this.model.get('notes').fetch();
return this;
},
As #user1248256 kindly helped me work out in the comments on my OP, the confusion was mainly in that I expected fetchRelated to pull down lazy-loaded records - that's actually not the case.
As a side-note, this view is actually a modal and be opened and closed (removed from the page). To prevent the zombie events problem described in this excellent post, I also manually unbind the events mentioned above.
Related
What is the idiomatic way to create a new Instance of an associated Model inside a Controller?
Motivation:
If I change the Class of my Model the code below doesn't get updated and I have to find all the breakages and fix them manually.
If I could use the the association in the controller, it gets updated automatically, but I can't find any documentation on the magical incantation to create a new instance from the controller reference.
Here is the relevant parts of my controller:
Ext.define('AdminApp.controller.SelectFilesController', {
extend: 'Ext.app.Controller',
models: [
'File'
],
// lots of stuff snipped for brevity
onFilefieldChange: function(filefield, value, eOpts) {
Ext.each(Ext.getDom('select-upload-button-fileInputEl').files, function(f) {
var fm = new AdminApp.model.File({
name: f.name,
size: f.size,
type: f.type,
md5: '',
status: 0
});
}
});
// lots more stuff snipped for brevity
}
What I want to know:
I found this in the documentation:
It’s important to note that the getters for both views and models
return a reference to the class (requiring you to instantiate your own
instances), while the getters for stores and controllers return actual
instances.
I can't find any examples of what the code to instantiate an instance should look like.
After much trial and error and just plain educated guessing ...
I figured out what the syntax should be.
First you need to create a reference to the class of the Model.
By convention this is the name of the model prefixed with get and suffixed with Model.
var fmc = this.getFileModel();
I had to do this outside the Ext.each() function that visits each item because the this reference pointed to an HTML5 File object instead of my Controller.
Then you simply use a regular Ext.create(fmc, { /* config */ } to get a new instance like so.
var fm = Ext.create(fmc, {
name: f.name,
size: f.size,
type: f.type,
md5: '',
status: 0
});
So the correct version of the onFilefieldChange function in the question should look like:
onFilefieldChange: function(filefield, value, eOpts) {
var fmc = this.getFileModel();
Ext.each(Ext.getDom('select-upload-button-fileInputEl').files, function(f) {
var fm = Ext.create(fmc,{
name: f.name,
size: f.size,
type: f.type,
md5: '',
status: 0
});
}
});
}
I have a model which has HasMany items in it.
var Checklist = Backbone.RelationalModel.extend( {
url: {{ url }}
relations: [ {
type: Backbone.HasMany,
key: 'items',
relatedModel: ChecklistItem,
collectionType: ChecklistItemCollection,
}],
});
I instantiate the model var checklist = new Checklist();
now I initialize Grid and fetch the checklist.
var grid = new Backbone.Grid({columns:columns, collection: checklist.get('items'));
checklist.fetch({reset:true});
I can see in Checklist's parse method that it has retrieved data from the server.
But the grid view doesn't show any data for it.
(When I used plain Backbone.model instead of backbone.RelationalModel, everything worked fine. So I know my setup is correct other than the backbone-relational + backgrid interaction is missing)
I'm new to backbone/javascript/backgrid/... world
I guess I need to hook up some events to make it work.
Please share an insight!
I have a basic Backbone application which obtain an array of JSON objects from a remote service and displays them: all good so far. However, each JSON object has an array of tags and I want to display the tags in a separate area of the webpage.
My question is: what is the most Backbone-friendly way of doing this? I could parse the existing data again in a second view, which is cleaner but takes up more computation (processing the entire array twice).
An alternative is gathering up the tag information in the primary view as it is working through the array and then passing it along to the subsidiary view, but then I'm linking the views together.
Finally, I'd like to filter based on those tags (so the tags will become toggle buttons and turning those buttons on/off will filter the information in the primary view); does this make any difference to how this should be laid out?
Bonus points for code snippets.
Hm. I'm not sure if this is the Backbone-friendly way, but I'll put the logic to retrieve a list of tags (I think that's what you meant by "parse") in the collection.
Both the main view and the subview will "listen" to the same collection, and the subview will just call collection.getTags() to get a list of tags it needs.
// Model that represents the list data
var ListDataModel = Backbone.Model.extend({
defaults: function() {
return {
name: null,
tags: []
};
}
});
// Collection of list data
var ListDataCollection = Backbone.Collection.extend({
model: ListDataModel,
initialize: function() {
var me = this;
// Expires tag collection on reset/change
this.on('reset', this.expireTagCache, this);
this.on('change', this.expireTagCache, this);
},
/**
* Expires tag cache
* #private
*/
expireTagCache: function() {
this._cachedTags = null;
},
/**
* Retrieves an array of tags in collection
*
* #return {Array}
*/
getTags: function() {
if (this._cachedTags === null) {
this._cachedTags = _.union.apply(this, this.pluck('tags'));
}
return this._cachedTags;
},
sync: function(method, model, options) {
if (method === 'read') {
var me = this;
// Make an XHR request to get data for this demo
Backbone.ajax({
url: '/echo/json/',
method: 'POST',
data: {
// Feed mock data into JSFiddle's mock XHR response
json: JSON.stringify([
{ id: 1, name: 'one', tags: [ 'number', 'first', 'odd' ] },
{ id: 2, name: 'two', tags: [ 'number', 'even' ] },
{ id: 3, name: 'a', tags: [ 'alphabet', 'first' ] }
]),
},
success: function(resp) {
options.success(me, resp, options);
},
error: function() {
if (options.error) {
options.error();
}
}
});
}
else {
// Call the default sync method for other sync method
Backbone.Collection.prototype.sync.apply(this, arguments);
}
}
});
var listColl = new ListDataCollection();
listColl.fetch({
success: function() {
console.log(listColl.getTags());
}
});
I guess two reasons for handling this in the collection:
It keeps the View code cleaner (This is given that we are not doing very complex logic in the tag extraction - It's just a simple _.pluck() and _.union().
It has 0 business logic involved - It can arguably belong to the data layer.
To address the performance issue:
It does go through the collection twice - However, if the amont of data you are consuming is too much for the client to process even in this case, you may want to consider asking the Backend to provide an API endpoint for this. (Even 500 pieces of data with a total of 1000 tags shouldn't bee too much for a somewhat modern browser to handle nowadays.)
Hmm. Does this help?
JSFiddle to go with this with the collection and the model: http://jsfiddle.net/dashk/G8LaB/ (And, a log statement to demonstrate the result of .getTags()).
When creating new collection (Choices) I want to set a property on it (ex: _question) which links back to the containing Model (MultipleChoiceQuestion)
This took me quite a bit of time to figure out, so in case somebody in the future has this problems...here's the code I ended up writing.
I discovered, unlike Model, Collection's initialize() function accepts 2 parameters. The first is models (which is a list of models you can initialize the collection with). The second is options (what you want). For a while my Collection started out with 1 model inside and I couldn't figure out why. Turns out I was passing my options into the models field.
THE CONTAINING MODEL:
m.MultipleChoiceQuestion = Backbone.Model.extend({
initialize: function(){
//NULL as first parameter because we don't want models
this.choices = new c.Choices(null, {
_question: this //this is referring to current question
}); //choices Collection is this
}
});
THE COLLECTION
c.Choices = Backbone.Collection.extend({
initialize: function(models, options){
this._question = options._question;
},
model: m.Choice
});
I actually found that although my 1st answer technically works, there's a plugin that makes care of storing collections in models (and creating appropriate One->Many, One->One and Many->One relationships
https://github.com/PaulUithol/Backbone-relational
Using that plugin you store the parent question as an ATTRIBUTE
m.MultipleChoiceQuestion = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'choices', //says to store the collection in the choices attribute
relatedModel: m.Choice, //knows we are talking about the choices models
includeInJSON: true, //when we do toJSON() on the Question we want to show serialize the choices fully
reverseRelation: {
key: 'question', //in the CHOICE object there will be an attribute called question which contains a reference to the question
includeInJSON: false //when we do .toJSON on a CHOICE we don't want to show the question object (or maybe we want to show the ID property in which case we set it to "id")
}
}],
coolFunction: function () {
this.get('choices').each(function(choice){
choice.doSomethingChoicey();
});
}
});
So now if we are in the choices model we can fully reference anything in the parent question:
m.Choice = m.RelationalModel.extend({
coolFunction: function(){
this.get('question').doSomemethingQuestiony();
var question_numer = this.get('question').get('question_number');
}
});
I have been struggling with a form in one of my Backbone views. This form is supposed to save the information for a project model (e.g. project name, project description, project members). While the project-specific information is saved without any issues into the corresponding database table, I did not manage to save the project-user relationships in a joint database table (projects_users, contains the corresponding ids for the two entities). The users that can be added to the project in the form are already present in the database, so nothing needs to be added into the users database table.
Could anyone put me on the right track here? I tried learning about relations in Backbone. These are two of the links that I have already looked into, but could not translate their content into a solution:
Backbone-relational
Model relationships in Rails and Backbone
Thank you,
Alexandra
EDIT
It was suggested that some code from my side would be useful. Since I do not have a good understanding of what I need to do, my code is pretty much a mess right now ... but let me try.
My form view:
App.Views.Projects.Common.Form = Backbone.View.extend({
...
submitted: function(formElement) {
var newData = this.serializeFormData(formElement);
this.model = new App.Models.Project({
name : newData.name,
description : newData.description
// Somehow put the users array associated with the project here ...
});
this.saveFormData(newData);
return false;
},
serializeFormData: function(formElement) {
var fields = formElement.serializeArray();
var serializedData = {};
$.each(fields, function(index, field) {
serializedData[field.name] = field.value;
});
return serializedData;
},
saveFormData: function(newData) {
var project = this.model;
// placeholder for the users that would be associated with the project
// parsing of the data from the form is required to get a corresponding array of user models
var users = App.users;
project.attributes.users = users;
// this line should save the project to the database table and the project-users relationships
// in the projects_users table; it needs the success and error functions
project.save({}, {});
},
...
})
For the project and user model files, I was thinking along these lines:
App.Models.Project = Backbone.RelationalModel.extend({
urlRoot: '/projects',
// Default attributes for the project.
defaults: {
description: "",
users: []
},
relations: [{
type : Backbone.HasMany,
key : 'users',
relatedModel : 'App.Models.User'
}]
});
App.Models.User = Backbone.RelationalModel.extend({
getId: function() {
return this.get('id');
},
getName: function() {
return this.get('name');
},
getEmail: function() {
return this.get('email');
}
});
Although the same information can be found as one of the comments to my question, I was asked to mark this as the answer, to make it easy for other people on StackOverflow. The solution that worked for me can be found here - see my own answer.