Backbone Menu Not Sorting - javascript

I'm having trouble getting a Backbone collection to sort properly. I inherited the project, so there may be some shenanigans someplace else, but I want to rule out any syntax error on my part.
The project uses a JSON file to handle the data:
"classifications": [
{
"name": "1 Bedroom",
"alias": "1BR",
"id": "1BR",
"menu_desc": "Residences"
},
{
"name": "2 Bedroom",
"alias": "2BR",
"id": "2BR",
"menu_desc": "Residences"
},
{
"name": "3 Bedroom",
"alias": "3BR",
"id": "3BR",
"menu_desc": "Residences"
},
{
"name": "4 Bedroom",
"alias": "4BR",
"id": "4BR",
"menu_desc": "Residences"
},
{
"name": "Common Areas",
"alias": "Common",
"id": "Common",
"menu_desc": "Resident Amenities"
}
]
Previously, there were no one-bedroom units, and the order in which it rendered was this:
I added the one-bedroom classification, and suddenly the order was this:
I did some digging and found documentation about the comparator property, but it only seems to apply to collections. This project doesn't use a collection for the classifications. It does for the submenu items (which floor the units are on, etc.), but not the main menu:
var MenuClassificationListView = Backbone.View.extend({
id: "classification_accordion",
template: _.template( "<% var classifications = this.options.classifications; _.each(this.collection.attributes, function(v,k) { %>"+
"<h3 class='<%= k %>'><%= classifications.get(k).get('name') %>"+
"<p><%=classifications.get(k).get('menu_desc')%></p></h3>"+
"<% var model = new MenuClassificationList(v); var view = new MenuClassificationItemView({collection:model, classification:k}); %>"+
"<% print(view.render().el.outerHTML); %>"+
"<% }); "+
"%>"),
render: function(){
//console.log(this.options.classifications);
//console.log(this.collection.attributes);
//alert(1);
this.$el.html(this.template());
return this;
}
});
How do I incorporate the comparator?
Thanks,
ty

One way could be to define a collection for the classifications, same way they are defined for the other items you mention:
var Classifications = Backbone.Collections.extend({ // etc. etc.
That way you can add the comparator and it will always be sorted.
Another way is to sort (http://underscorejs.org/#sortBy) the array in the initialize function in your view:
initialize: function(options) { // sorry don't remember the exact syntax for the parameters passed in, but I believe options is what you need
this.options.sortedclassifications = _sortBy(options.classifications, function (c) { return parseInt(c.id); }); // or any other sorting logic
}
Then in the template use the sorted classifications:
template: _.template( "<% var classifications = this.options.sortedclassifications; _.each(this.collection.attributes, function(v,k) { %>" + // etc. etc.
This should give you what you need. However, if I may add a personal opinion, I would go through the effort of defining a Collection for the classifications and a model for the single classification. Moreover, I would keep the MenuClassificationListView but also create a MenuClassificationView that will hold the single classification template.
In this way you are able to compose views, change rendering of the single classification without changing the list and scope the events to the inner views (so clicking on a single classification is handled by the single classification view). It makes everything cleaner, more composable and readable, in my opinion.

_.sortBy does not need to be used as Backbone collections already come with built in functionality for sorting.
See: http://backbonejs.org/#Collection-comparator
Example:
var SortedCollection = Backbone.Collection.extend({
comparator: 'key'
});
var mySortedCollection = new SortedCollection([{a:5, key:2}, {key:1}]);
console.log( mySortedCollection.toJSON() );
// [{key:1}, {a:5, key:2}]
However, the collection will not be automatically re-sorted when changing the key attribute. See:
mySortedCollection.at(0).set( 'key', 3 );
console.log( mySortedCollection.toJSON() );
// [{key:3}, {a:5, key:2}]
You have multiple options to solve this problem: you can manually call mySortedCollection.sort() or you can initialize the collection by binding its change:key event to re-sort the collection. The change:key event is triggered by the model whose key attribute is changed. This event is automatically propagated to the collection.
var AutoSortedCollection = Backbone.Collection.extend({
comparator: 'key',
initialize: function() {
this.listenTo( this, 'change:key', this.sort );
}
});
In addition, I suggest removing functionality from the templates. It is easy to debug Backbone Views, but it gets harder to read the stack trace as you move functionality inside the template string. You also enforce proper separation of concerns by using your Backbone View for preparing all data for presentation and your template should just display it.
var MyView = Backbone.View.extend({
//...
serializeData: function() {
return {
classifications: this.collection.toJSON(),
keys: this.collection.length > 0 ? this.collection.at(0).keys() : []
}; // already sorted
}
render: function() {
this.$el.html(this.template( this.serializeData() ));
}
});
Your template string becomes much easier to read: you can directly use the variables classifications and keys, iterate on them with _.each and simply reference to values without having to deal with the Collection syntax.

Related

Backbone change event not firing when certain attributes are changed

In my backbone application, I have a model that looks a little like this,
{
"id" : 145,
"name" : "Group Number 1",
"information" : "Some kind of blurb about group number 1",
"members" : {[
"id" : 1,
"first_name" : "John",
"last_name" : "Doe",
"email" : "johndoe#goog.ecom"
]}
}
Now if I run this.model.get('members').add(newUser) a new user gets added to the members collection within my model - however it does not fire a change event, why is this? Buy yet if I change the name of the model, then a change event is fired?
All this is done with a view that looks like this,
Individual model view
Views.OrganisationView = Backbone.View.extend({
tagName: 'div',
className:'group group--panel col-sm-3',
template : _.template( $('#tpl-single-group').html() ),
events: {
"click a[data-type=organisation], button[data-type=organisation]" : "edit",
"click .js-delete-group" : "removeOrganisation",
},
initialize: function() {
this.model.on("error", function(model, xhr, options){
console.log(model, xhr, options);
console.log(this);
});
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.removeView);
},
render: function() {
this.$el.html( this.template({
group: this.model.toJSON()
}));
return this;
},
removeView: function() {
this.remove();
},
removeOrganisation: function(e) {
this.model.destory();
this.remove();
},
edit: function(e) {
e.preventDefault();
Routes.Application.navigate('/organisation/edit/' + this.model.get('id'), { trigger: false } );
var editClient = new Views.OrganisastionEditView({
model: this.model
});
}
});
The second confusing thing that a request event gets thrown, (makes sense seen as though I am saving the model, but an error event gets thrown as well, but there are no errors the xhr and I am not currently validating the model?
Here is how I am saving the user to members collection in my model,
var member = new Pops.Models.User({ id: element.data('id') });
member.fetch({
success:function() {
self.model.get('members').add(member);
var model = self.model;
self.$('.search').hide();
self.$('button').show();
var projectMember = new Pops.Views.UserInitialsWithAdmin({
model: member
});
self.model.save({validate:false});
self.$('.search').parent().append( projectMember.render().el );
self.$('.search').remove();
}
});
(I'm assuming the first bit of code you've given is just a guideline of what a plain JSON representation of your model would look like, and that members is a real Collection with an add method available.)
In answer to the first question: change events are only fired when changing a model attribute using set. In your case, you're adding to the collection stored in the members attribute, but the members attribute still contains a reference to the same collection it did before, which means from Backbone's perspective this attribute has not changed. I would suggest attaching listeners directly to the members collection. Also see How can I "bubble up" events on nested Backbone collections?.
In general nesting models in Backbone is not straightforward, as Jeremy Ashkenas has pointed out. It's often better to keep models flat and store references to related models as arrays of ids, which can then be fetched as necessary.

Backbone and best practice getting config JSON

I've got a JSON file that looks like this.
{
"config": {
"setting1": 'blabla',
"setting2": 'blablabla'
},
"content": {
"title": "Title of an exercise.",
"author": "John Doe",
"describtion": "Exercise content."
},
"answers": [
{
"id": "1",
"content": "Dog",
"correct": true
},
{
"id": "2",
"content": "Fish",
"correct": false
}
]
}
Than, I create a Backbone View, combined from content model, and answers (which are randomly selected, but It's not most important now).
I've also got a config, which has settings that will determinate which view and collection methods to use.
It seems like a simple task, but as I'm new to Backbone, I'm wondering which is the best way to fetch JSON file, creating one model with url to JSON and than using parse and initialize creating another models and collections (with answers), or using $.getJSON method that will create exactly the models that I need?
I was trying using $.getJSON
$.getJSON(source, function(data) {
var contentModel = new ContentModel(data.content);
var contentView = new ExerciseView({ model: contentModel });
var answerCollection = new AnswersCollection();
_.each(data.answers, function(answer) {
answerCollection.add(answer);
});
var answersView = new AnswersView({collection: answerCollection});
$(destination).html( contentView.render().el );
$('.answers').append( answersView.el );
)};
But It doesn't seem very elegant solution, I know that this application needs good architecture, cause It will be developed with many other Views based on 'config'.
Hope you guys give me some suggestions, have a good day!
I think what you've done works fine and is correct. But you may need to refactor a little bit since "it will be developed with many other Views based on 'config'".
IMHO, the first thing you need to do is to handle failure in your getJson callback to make the process more robust.
Second, it is useful to create a Factory to generate your views because your logic is to generate different views based on the config data from server. So the factory maybe:
contentViewFactory.generate = function(data) {
var config = data.config;
....
var ActualContentView = SomeContentView;
var contentModel = new ContentModel(data.content);
return = new ActualContentView({ model: contentModel });
}
If your logic is simple, you can have a dict map from config to view class like:
var viewMaps = {
"exercise" : ExerciseView,
"other": SomeOtherView,
//....
}
And if every workflow has a AnswersView you can keep that in your getJSON callback. So maybe now your getJSON looks like this:
$.getJSON(source, function(data) {
// keep the config->view logic in the factory
var contentView = contentViewFactory.generate(data);
var answerCollection = new AnswersCollection();
_.each(data.answers, function(answer) {
answerCollection.add(answer);
});
var answersView = new AnswersView({collection: answerCollection});
$(destination).html( contentView.render().el );
$('.answers').append( answersView.el );
})
.fail(){
//some failure handling
};
Furthermore, if you have common logics in you "ContentView"s, it's natural that you can have a "BaseContentView" or "ContentViewMixin" to extract the common logic and use extends to make your code more OO:
Backbone.View.extend(_.extend({}, ContentViewMixin, {
//.....
}
So if someone is trying to add a new ContentView, he/she just needs to add some code in the factory to make the new View be generated by config. Then extends the ContentViewMixin to implement the new View.

Mapping JSON to backbone.js collections

Alright, it looks like I need a hint to point me in the right direction. This question is two part - working with mult-dimensional JSON and Collections of Collections from JSON.
Background
I have some JSON that is going to be retrieved from a server and have control over how it could be formatted.
Multi-Dimentional JSON
I'm having some trouble being able connecting the model to the parts in the JSON. Say I wanted to render just each of the posts author name, and the content of status in the sample JSON below. I'm having no problem getting the status into the model, but the author name I'm a bit confused how to get to it. From my understanding I have to override the parse.
Is this bad standards / is there a better JSON structure I should use? Would it be better to keep it as flat as possible? That is move the author name and photo up one level?
I was reading How to build a Collection/Model from nested JSON with Backbone.js but it is still a little unclear to me.
Collection in Collections
Is there a nice way to make a collection within a collection for backbone.js? I will have a collection of posts, and then would have a collection of comments on that post. As I'm developing in backbone is that even possible?
From what I understand in Backbone.js Collection of Collections and Backbone.js Collection of Collections Issue, it would look something like this?
var Comments = Backbone.Model.extend({
defaults : {
_id : "",
text : "",
author : ""
}
})
var CommentsCollection = Backbone.Collection.extend({ model : Comments })
var Posts = Backbone.Model.extend({
defaults : {
_id : "",
author : "",
status : "",
comments : new CommentsCollection
}
})
var PostsCollection = Backbone.Collection.extend({ model : Posts })
Sample JSON
{
"posts" : [
{
"_id": "50f5f5d4014e045f000002",
"author": {
"name" : "Chris Crawford",
"photo" : "http://example.com/photo.jpg"
},
"status": "This is a sample message.",
"comments": [
{
"_id": "5160eacbe4b020ec56a46844",
"text": "This is the content of the comment.",
"author": "Bob Hope"
},
{
"_id": "5160eacbe4b020ec56a46845",
"text": "This is the content of the comment.",
"author": "Bob Hope"
},
{
...
}
]
},
{
"_id": "50f5f5d4014e045f000003",
"author": {
"name" : "Chris Crawford",
"photo" : "http://example.com/photo.jpg"
},
"status": "This is another sample message.",
"comments": [
{
"_id": "5160eacbe4b020ec56a46846",
"text": "This is the content of the comment.",
"author": "Bob Hope"
},
{
"_id": "5160eacbe4b020ec56a46847",
"text": "This is the content of the comment.",
"author": "Bob Hope"
},
{
...
}
]
},
{
...
}
]}
I appreciate even any hints to guild me. Thanks!
It can be overwhelming when trying to write up code to make it work for nested objects. But to make it simpler lets break it up into smaller manageable pieces.
I would think in these lines.
Collections
Posts
Comments
Models
Post
Comment
Author
Main collection -- Posts collection
(Which contains list of Post Models)
And each model in the Posts collection will have 3 sets of attributes(May not be the right term).
1st - level of attributes (status , id).
2nd - Author attribute which can be placed in a separate Model(Authod Model).
3rd - Collection of comments for each Post Model.
Collection in Collections would be a bit confusing here.
As you would have Models in Collection(Post Model inside Posts Collection) and each Model will nest a collection again(Comments collection inside Post Model). Basically you would be Handling a Collection inside a Model.
From my understanding I have to override the parse.
Is this bad standards / is there a better JSON structure I should use?
It is a perfectly plausible solution to handle the processing this in the Parse method. When you initialize a Collection or a Model , Parse methods is first called and then initialize is called. So it is perfectly logical to handle the logic inside the Parse method and it is not at all a bad standard.
Would it be better to keep it as flat as possible?
I don't think it is a good idea to keep this flat at a single level, as the other data is not required on the first level in the first place.
So the way I would approach this problem is write up the parse method in the Post Model which processes the response and attach the Author model and Comments collection directly on the Model instead as an attribute on the Model to keep the attributes hash clean consisting of 1st level of Post data. This I feel will be cleaner and lot more scalable on the long run.
var postsObject = [{
"_id": "50f5f5d4014e045f000002",
"author": {
"name": "Chris Crawford",
"photo": "http://example.com/photo.jpg"
},
"status": "This is a sample message.",
"comments": [{
"_id": "5160eacbe4b020ec56a46844",
"text": "This is the content of the comment.",
"author": "Bob Hope"
}, {
"_id": "5160eacbe4b020ec56a46845",
"text": "This is the content of the comment.",
"author": "Bob Hope"
}]
}, {
"_id": "50f5f5d4014e045f000003",
"author": {
"name": "Brown Robert",
"photo": "http://example.com/photo.jpg"
},
"status": "This is another sample message.",
"comments": [{
"_id": "5160eacbe4b020ec56a46846",
"text": "This is the content of the comment.",
"author": "Bob Hope"
}, {
"_id": "5160eacbe4b020ec56a46847",
"text": "This is the content of the comment.",
"author": "Bob Hope"
}]
}];
// Comment Model
var Comment = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
text: "",
author: ""
}
});
// Comments collection
var Comments = Backbone.Collection.extend({
model: Comment
});
// Author Model
var Author = Backbone.Model.extend({
defaults: {
text: "",
author: ""
}
});
// Post Model
var Post = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
author: "",
status: ""
},
parse: function (resp) {
// Create a Author model on the Post Model
this.author = new Author(resp.author || null, {
parse: true
});
// Delete from the response object as the data is
// alredy available on the model
delete resp.author;
// Create a comments objecton model
// that will hold the comments collection
this.comments = new Comments(resp.comments || null, {
parse: true
});
// Delete from the response object as the data is
// alredy available on the model
delete resp.comments;
// return the response object
return resp;
}
})
// Posts Collection
var Posts = Backbone.Collection.extend({
model: Post
});
var PostsListView = Backbone.View.extend({
el: "#container",
renderPostView: function(post) {
// Create a new postView
var postView = new PostView({
model : post
});
// Append it to the container
this.$el.append(postView.el);
postView.render();
},
render: function () {
var thisView = this;
// Iterate over each post Model
_.each(this.collection.models, function (post) {
// Call the renderPostView method
thisView.renderPostView(post);
});
}
});
var PostView = Backbone.View.extend({
className: "post",
template: _.template($("#post-template").html()),
renderComments: function() {
var commentsListView = new CommentsListView({
// Comments collection on the Post Model
collection : this.model.comments,
// Pass the container to which it is to be appended
el : $('.comments', this.$el)
});
commentsListView.render();
},
render: function () {
this.$el.empty();
// Extend the object toi contain both Post attributes
// and also the author attributes
this.$el.append(this.template(_.extend(this.model.toJSON(),
this.model.author.toJSON()
)));
// Render the comments for each Post
this.renderComments();
}
});
var CommentsListView = Backbone.View.extend({
renderCommentView: function(comment) {
// Create a new CommentView
var commentView = new CommentView({
model : comment
});
// Append it to the comments ul that is part
// of the view
this.$el.append(commentView.el);
commentView.render();
},
render: function () {
var thisView = this;
// Iterate over each Comment Model
_.each(this.collection.models, function (comment) {
// Call the renderCommentView method
thisView.renderCommentView(comment);
});
}
});
var CommentView = Backbone.View.extend({
tagName: "li",
className: "comment",
template: _.template($("#comment-template").html()),
render: function () {
this.$el.empty();
this.$el.append(this.template(this.model.toJSON()));
}
});
// Create a posts collection
var posts = new Posts(postsObject, {parse: true});
// Pass it to the PostsListView
var postsListView = new PostsListView({
collection: posts
});
// Render the view
postsListView.render();
Check Fiddle
(Edited to correct my initial misreading of the question.)
There's no need to override parse method of the model unless you want to change its structure. But it sounds like you don't need to -- to render the author name, just use author.name in the view:
<%= author.name %>
As far as initializing the nested collection, your approach is exactly right. All you have to do is convert the JSON object to Backbone models, and pass them to the PostsCollection (the Backbone.Collection constructor accepts an array of Backbone models, not raw JSON). One way of doing this is to use map:
var postModels = json.posts.map(function(post) { return new Posts(post); });
var posts = new PostsCollection(postModels);
Note that you'll need to do something similar in the initialize method of the Posts model -- retrieve the comments JSON array, and convert it to an array of Comments models:
initialize: function() {
if (attributes.comments && attributes.comments.length > 0) {
var commentModels = attributes.comments.map(function(comment) {
return new Comments(comment);
});
this.set("comments", new CommentsCollection(commentModels));
}
}
Here is working example.
Update, I found a SuperModel for backbone which provides relationships between models and between collections. It has proved to be a great solution for Collections within Collections as well as Deep Nested Model data.
Models are pre-defined with their relationships to other models via key. During the initialize/parse of the model any values in the JSON at that key gets passed off to a new related model or collection. A relationship is created between the two models/collections.
This means with the above example we can do something like this with our models:
Setup
var Author = Supermodel.Model.extend({});
var Post = Supermodel.Model.extend({});
var Comment = Supermodel.Model.extend({});
var Posts = Backbone.Collection.extend({
model: function(attrs, options) {
return Post.create(attrs, options);
}
});
var Comments = Backbone.Collection.extend({
model: function(attrs, options) {
return Comment.create(attrs, options);
}
});
Post.has().one('author', {
model: Author,
inverse: 'post'
}).many('comments', {
collection: Comments,
inverse: 'post'
});
//reverse relationships could also be setup
Usage
var posts = new Posts( postsObject ); //where postsObject is an array of posts
//With SuperModel, we are able to navigate the related models
posts.first().comments();
posts.first().comments().author();
posts.last().author();
Fiddle
Working Example in JSFiddle

Looking for design pattern to create multiple models/collections out of single JSON responses

I have a Backbone application where the JSON I get from the server isn't exactly 1 on 1 with how I want my models to look. I use custom parse functions for my models, ex:
parse: function(response) {
var content = {};
content.id = response.mediaId;
content.image = response.image.url;
return content;
}
This works. But, in some cases I have an API call where I get lots of information at once, for instance, information about an image with its user and comments:
{
"mediaId": "1",
"image": {
"title": "myImage",
"url": "http://image.com/234.jpg"
},
"user": {
"username": "John"
},
"comments": [
{
"title": "Nice pic!"
},
{
"title": "Great stuff."
}
]
}
How would I go about creating a new User model and a Comments collection from here? This is an option:
parse: function(response) {
var content = {};
content.id = response.mediaId;
content.image = response.image.url;
content.user = new User(response.user);
content.comments = new Comments(response.comments);
return content;
}
The trouble here is, by creating a new User or new Comments with raw JSON as input, Backbone will just add the JSON properties as attributes. Instead, I'd like to have an intermediate parse-like method to gain control over the objects' structure. The following is an option:
parse: function(response) {
// ...
content.user = new User({
username: response.user.username
});
// ...
}
...but that's not very DRY-proof.
So, my question is: what would be a nice pattern to create several models/collections out of 1 JSON response, with control over the models/collections attributes?
Thanks!
It may not be the nicest way possible, but this is how I do it:
content.user = new User(User.prototype.parse(response.user));
The only problem is that the this context in User.parse will be wrong. If you don't have any specific code in the User constructor, you can also do:
content.user = new User();
content.user.set(user.parse(response.user));
I also noticed an interesting note in the Backbone version 0.9.9 change log:
The parse function is now always run if defined, for both collections and models — not only after an Ajax call.
And looking at the source code of Model and Collection constructor, they do it like so:
if (options && options.parse) attrs = this.parse(attrs);
Maybe upgrading to 0.9.9 will give you what you need? If upgrade is not an option, you can of course implement the same in your own constructor.

Iteration in handlebar using backbone

I'm using backbone and handlebars for templating and i'm new to this.
My current json is in the below format and the code works fine.
[
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
But when i change my json structure to something like shown below i'm having difficulty in getting things to be populated.
{
"total_count": "10",
"dataElements": [
{
"id": "10",
"info": {
"name": "data10"
}
},
{
"id": "11",
"info": {
"name": "data11"
}
}
]
}
How can i populate name, info and total_count keeping the current code structure ?
JSFiddle : http://jsfiddle.net/KTj2K/1/
Any help really appriciated.
A few things that you need to do in order for this to work.
Replace Backbone's core 'reset' on your collection with a custom one that understands the data you are passing to it. For example:
reset: function (data) {
this.totalCount = data.total_count;
Backbone.Collection.prototype.reset.call(this, data.dataElements);
}
Now when you reset your collection, it will pull the total_count out of the object you are resetting it with, and use Backbone's core reset with the dataElement array. Keep in mind you may have to do a similar thing with 'parse' if you're intending on pulling this from the server.
I'd recommend that (if your example looks anything like the real code you're working with) you reset your collection before getting to rendering.
var dataCollectionList = new dataCollection();
dataCollectionList.reset(jsonData);
var App = new AppView({model : dataCollectionList});
Now in your view's "render" method you can grab the 'totalCount' property off the collection -
render : function() {
//Should spit the total count into the element, just as an example
this.$el.append(this.model.totalCount);
//or console.log it
console.log(this.model.totalCount);
return this;
}
Voila. Side note - as someone who works with Backbone a lot, it drives me nuts when people set an attribute of something like "model" (i.e. peopleModel, itemModel, etc) and it ends up being a backbone collection. It's much clearer to name it after what it is - though some MVC purists may disagree a bit.
Also, in this code block:
_.each(this.model.models, function (myData) {
$(this.el).append(new ItemView({model:myData}).render().el);
}, this);
You don't need to do _.each(this.model.models.......). Since you're working with a collection, the collection has a built in 'each' method.
this.model.each(function (myData) { ..... } , this);
Quite a bit cleaner.

Categories

Resources