search
HomeWeb Front-endHTML TutorialGet started blogging with Parse.js: delete, logout, and view individual blog posts

开始使用 Parse.js 创建博客:删除、注销和查看个人博客文章

In the last session, you restructured the entire blog system. Now that everything is cleared up, you're ready to get up to speed on some new adventures. In this session we'll do a little more work around the router and add three features to our blogging system: delete, logout, and a single blog view.

1. delete

In Part 6, we introduced the editing capabilities. You will most likely also want to delete one of your blog posts. There are two places to put this function: add it to BlogsAdminView, or send it to a URL and handle it in Router.

I will show you the router way. It is more commonly used and makes the code more structured.

Step 1: Add URL Pattern

As usual, we start by adding a URL pattern:

	routes: {
		'': 'index',
		'admin': 'admin',
		'login': 'login',
		'add': 'add',
		'edit/:id': 'edit',
		'del/:id': 'del'
	}

Then, update the link in the admin page:

	
	Delete

Step 3: del function

Now, let's add a new del function to Router to handle it. It's very simple: find the blog post using the id we passed in from the URL, and destroy it.

Try to challenge yourself to write my code without reading it. At this point you should have a good grasp of Parse.js.

	del: function(id) {
		var query = new Parse.Query(Blog);
		query.get(id).then(function(blog){
			blog.destroy().then(function(blog){
				alert('Deleted!');
			})
		});
	}

Note that you can use the .then() function here instead of passing an object like we did before:

	query.get(id, {
		success: function(blog) {
			...
		},
		error: function(blog, error) {
			...
		}
	});

This is an easy way to add callback functions in Parse.js, making your code cleaner and more readable. Visit Parse.com for complete documentation on Promises.

Let's give it a test run and double check the database to see if it's working properly.

开始使用 Parse.js 创建博客:删除、注销和查看个人博客文章

Congratulations, it's working!

Step 4: Redirect back to the admin page

If you pay attention to the URL, you will find that after clicking out of the warning box, the URL is still /del/, and the post you just deleted still exists. We want to send the user back to the admin page after deletion and the page should refresh and reflect the changes they just made.

You can achieve all of this with redirects:

	del: function(id) {
		var self = this,
			query = new Parse.Query(Blog);
		query.get(id).then(function(blog){
			blog.destroy().then(function(blog){
				self.navigate('admin', { trigger: true });
			})
		});
	}

Note that because this time you are calling navigate from inside the router, you can store the router as self and then call self.navigate() .

Step 5: Check Login

Finally, we need to make sure you are the only one who can delete your blog posts. Let's check the login of this function. This should be the same as the edit function.

	del: function(id) {
		if (!Parse.User.current()) {
			this.navigate('#/login', { trigger: true });
		} else {
			...
		}
	}

2. Logout

Like deletion, logout can also be handled by the router. It also starts with adding the URL pattern:

	routes: {
		...
		'logout': 'logout'
	},

The logout functionality itself in Parse.js is very simple. Just call Parse.User.logOut() and redirect to the /login page:

	logout: function () {
		Parse.User.logOut();
		this.navigate('#/login', { trigger: true });
	}

Finally, let’s add a button to #admin-tpl:

      Logout

开始使用 Parse.js 创建博客:删除、注销和查看个人博客文章

As you can see, styling is really not the focus of this tutorial. Feel free to fix the padding and style it however you want.

3. Single blog view

Now let's move on to some new features.

As of now, we are displaying the entire blog post on the home page. While some people do prefer this style, most blogging systems support the idea of ​​providing a snippet excerpt up front, and if a visitor clicks on the article, they can see the content on a separate page, possibly with some comments area around it.

I will walk you through creating this detailed single blog view in this session, and we will focus on building comments in the next session.

Step 1: Add Summary Column

First, we add a column as a summary to the blog table:

开始使用 Parse.js 创建博客:删除、注销和查看个人博客文章

Step 2: Include summary in WriteBlogView

Now, let's add this to the Blog.update() function. You can change the function to get a data object containing title, summary, and content to avoid having to remember the order of the variables.

	update: function(data) {
		// Only set ACL if the blog doesn't have it
		...
		
		this.set({
			'title': data.title,
			'summary': data.summary,
			'content': data.content,
			...
		}).save(null, {
			...
		});
	}

Add another <textarea></textarea> in #write-tpl as a summary:

	// Put this form-group in between the form-group for title and content
	
		Summary
		{{summary}}
	

并相应地更改 WriteBlogView.submit() 函数:

	submit: function(e) {
		...
		this.model.update({
			title: data[0].value, 
			summary: data[1].value,
			content: data[2].value
		});
	}

现在,由于我们在模板中添加了一个新变量,因此我们需要在 WriteBlogView.render() 函数中为其指定一个默认的空值:

	render: function(){
		...
		
		if (this.model) {
			...
		} else {
			attributes = {
				form_title: 'Add a Blog',
				title: '',
				summary: '',
				content: ''
			}
		}
		...
	}

如果您对内容使用 wysihtml5 插件,您会注意到之前我们的目标是所有 <textarea></textarea> 元素:

this.$el.html(this.template(attributes)).find('textarea').wysihtml5();

让我们为内容文本区域指定一个类,并仅使用 wysihtml5 插件来定位该类。

#write-tpl中:

	{{{content}}}

WriteBlogView.render()函数中:

this.$el.html(this.template(attributes)).find('.write-content').wysihtml5();

现在可以使用了!

开始使用 Parse.js 创建博客:删除、注销和查看个人博客文章

第 3 步:在主页上显示摘要

使用新的撰写博客页面并添加一些带有摘要的博客文章,并提取摘要而不是#blogs-tpl中的内容:

	{{#each blog}}
	
		{{title}}
		At {{time}} by {{authorName}}
		{{summary}}
	
	{{/each}}

第 4 步:添加 SingleBlogView 页面

花一点时间考虑一下如何添加 /blog/:id 页面来显示每篇博客文章的内容,并尝试自己完成。您现在应该能够自己完成这一切了!

但为了本教程的目的,让我给您快速演练:

为此页面添加新的 HTML 模板:

	
		<div class="blog-post">
			<h2 id="title">{{title}}</h2>
			<p class="blog-post-meta">At {{time}} by {{authorName}}</p>
			<div>{{{content}}}</div>
		</div>
	

添加一个新的 BlogView 类,该类接受 blog 对象,并将其呈现在 #blog-tpl 中: p>

	BlogView = Parse.View.extend({
		template: Handlebars.compile($('#blog-tpl').html()),
		render: function() { 
			var attributes = this.model.toJSON();
			this.$el.html(this.template(attributes));
		}
	}),

BlogRouter 中添加新的 URL 模式:

	routes: {
		...
		'blog/:id': 'blog',
		...
	}

并在 BlogRouter.blog() 函数中,通过 id 获取博客,渲染一个 blogView,并将其放入 $container:

	blog: function(id) {
		var query = new Parse.Query(Blog);
		query.get(id, {
			success: function(blog) {
				console.log(blog);
				var blogView = new BlogView({ model: blog });
				blogView.render();
				$container.html(blogView.el);
			},
			error: function(blog, error) {
				console.log(error);
			}
		});
	}

最后,更新#blogs-tpl中的链接以链接到此页面:

	{{#each blog}}
	
		{{title}}
		At {{time}} by {{authorName}}
		{{summary}}
	
	{{/each}}

尝试一下:

开始使用 Parse.js 创建博客:删除、注销和查看个人博客文章

如果您自己完成此操作,可加分。

结论

在本次会议中,您构建了很多内容:删除功能、注销功能和另一种新页面类型。如果您到目前为止一直在关注本教程系列,我认为您对数据库、模型、视图、模板和路由器如何协同工作有深入的了解。我希望您现在也开始喜欢构建 Parse.js 项目。请留下您的反馈并告诉我是否有帮助。

通过我们这次构建的这个单一博客文章页面,我们下次将添加评论部分。应该是一件有趣的事。敬请关注!

The above is the detailed content of Get started blogging with Parse.js: delete, logout, and view individual blog posts. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.