Advertisement
  1. Code
  2. JavaScript

Get Started Building Your Blog With Parse.js: Categories

Scroll to top
Read Time: 5 min
This post is part of a series called Building Your Blog with Parse.js.
Get Started Building Your Blog With Parse.js: Comments
Get Started Building Your Blog With Parse.js: Migration to Your Own Parse Server
Final product imageFinal product imageFinal product image
What You'll Be Creating

First of all, welcome to the finale of this tutorial series!

Last session, I showed you how to add a new function to the blog: adding comments. It’s pretty much a stand-alone feature. This session, I will show you how to add categories to your blog system. It’s a more difficult task, as its code will be more closely intertwined with the existing code.

Category Model

Step 1: Category Class

You know the drill: the model always comes first. One more new class on Parse.com: the Category class. It should be very simple. We only need one custom field:

  • String name

Let’s just create two dummy categories to make it easier for testing:

categoriescategoriescategories

Step 2: Category Field in the Blog Class Table

Now, add a new column in the Blog class table on Parse.com and make it a pointer to Category.

pointerpointerpointer

Let’s also link them to several blog posts.

postspostsposts

Step 3: Comment Object

Next, the Comment object in blog.js. Again, it can be very simple.

1
2
Category = Parse.Object.extend('Category', {});

Step 4: Comments Collection

And the collection:

1
2
Categories = Parse.Collection.extend({
3
	model: Category
4
})

Add a Category Dropdown in the Write a Blog Form

Step 1: Fetch Categories

Like in Comments, let’s fetch comments when we render WriteBlogView.

1
2
render: function(){
3
	...
4
	var self = this,
5
		categories = new Categories();
6
	categories.fetch().then(function(categories){
7
		attributes.categories = categories.toJSON();
8
		self.$el.html(this.template(attributes)).find('.write-content').wysihtml5();
9
	});
10
}

Step 2: Find the Current Category

Next, we need to find the current category when there’s an existing category for the blog post you are editing. We can just loop through the attribute.categories array and set selected to TRUE for the correct category.

1
2
categories.fetch().then(function(categories){
3
	attributes.categories = categories.toJSON();
4
	// Get current selected category
5
	if (attributes.category) {
6
		attributes.categories.forEach(function(category, i){
7
			if (category == attributes.category) {
8
				attributes.categories[i].selected = true;
9
			}
10
		});
11
	}
12
	console.log(attributes);
13
	self.$el.html(self.template(attributes)).find('.write-content').wysihtml5();
14
});

Step 3: Render Categories in a Dropdown Menu

And in HTML, render categories in a <select> menu:

1
2
3
	Category
4
	
5
		{{#each categories}}
6
		{{name}}
7
		{{/each}}
8
	
9

Step 4: Record the Selected Category

Now let’s record it in the submit() function in WriteBlogView:

1
2
submit: function(e) {
3
	...
4
	this.model.update({
5
		title: data[0].value,
6
		category: data[1].value,
7
		summary: data[2].value,
8
		content: data[3].value
9
	});
10
}

And then in the Blog.update() function:

1
2
Blog = Parse.Object.extend('Blog', {
3
	update: function(data) {
4
		...
5
		var category = new Category();
6
		category.id = data.category;
7
		this.set({
8
			'title': data.title,
9
			'category': category,
10
			...
11
		}).save(null, {
12
			...
13
		});
14
	}
15
})

Notice that you can’t just put down the category id, but you need to create a new category instance, and set its id to the category id you get from the form.

Give it a test, and hopefully you can see it correctly recorded in the database:

New PostNew PostNew Post

Category Pages

Now let’s move on to create a sidebar that links to different categories.

Step 1: Clean Up and Make a Template

First, take out all the static HTML code for the sidebar:

1
2

And then make a new template div for the template of category menu:

1
2
3
	<div class="sidebar-module">
4
		<h4>Categories</h4>
5
		<ol class="list-unstyled">
6
			{{#each category}}
7
			<li><a href="#/category/{{objectId}}">{{name}}</a></li>
8
			{{/each}}
9
		</ol>
10
	</div>
11

Step 2: CategoriesView

Then, make a View for this list of categories:

1
2
CategoriesView = Parse.View.extend({
3
	template: Handlebars.compile($('#categories-tpl').html()),
4
	render: function() { 
5
		var collection = { category: this.collection.toJSON() };
6
		this.$el.html(this.template(collection));
7
	}
8
})

Step 3: Render CategoriesView

Because the list of categories is on every page, we can create a shared variable in BlogRouter.initialize():

1
2
initialize: function(options){
3
	this.blogs = new Blogs();
4
	this.categories = new Categories();
5
}

And then render it in the .start() function:

1
2
start: function(){
3
	...
4
	this.categories.fetch().then(function(categories){
5
		var categoriesView = new CategoriesView({ collection: categories });
6
		categoriesView.render();
7
		$('.blog-sidebar').html(categoriesView.el);
8
	});
9
}

Give it a try, and now it renders:

sidebarsidebarsidebar

Because we now have a shared variable, we can also use it in WriteBlogView.render():

Step 4: Add Router

Now we just need to make /category/{{objectId}} work.

Let’s add this router pattern first:

1
2
routes: {
3
	...
4
	'category/:id': 'category'
5
}

Then, write the category function. It’s fairly straightforward, just a combination of the things you’ve learnt so far:

1
2
category: function(id) {
3
	// Get the current category object
4
	var query = new Parse.Query(Category);
5
	query.get(id, {
6
		success: function(category) {
7
			// Query to get the blogs under that category
8
			var blogQuery = new Parse.Query(Blog).equalTo("category", category).descending('createdAt');
9
			collection = blogQuery.collection();
10
			// Fetch blogs
11
			collection.fetch().then(function(blogs){
12
				// Render blogs
13
				var blogsView = new BlogsView({ collection: blogs });
14
				blogsView.render();
15
				$container.html(blogsView.el);
16
			});
17
		},
18
		error: function(category, error) {
19
			console.log(error);
20
		}
21
	});
22
}

Now everything’s working.

categoryPagecategoryPagecategoryPage

Conclusion

Wow, I can’t believe it took me this long to finish the whole series. In the past ten sessions, you’ve learnt a lot about Parse.js and web development in general. Together we’ve built a blog system with full functions: add, edit, delete, login, comments, and in this session, categories.

I hope you find this series helpful. Please share with me your feedback, suggestions, and content you want me to cover in the future. And if you made any web projects using techniques from this tutorial, I would love to see them, too.</select>

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.