Twitter如何更新其博客帖子?

时间:2013-02-20 08:01:04

标签: php javascript jquery blogs comet

我们正在从头开始为我们公司创建一个博客,我们通过PHP和jQuery中的彗星使得新博客文章能够更新成为可能。

但是后来我们意识到,如果用户编辑或删除了他们自己的博客帖子,这是在页面的一半?我们如何更新?

更新:哎呀,我刚刚意识到如果博客文章被删除,Twitter不会立即删除它。但是,拥有这样的功能会更好。

1 个答案:

答案 0 :(得分:3)

由于您使用的是Comet解决方案,因此您可能正在关注某种publish-subscribe pattern

从那里,您可以通过几种方式实现您的目标。一种解决方案是为页面上可见的每篇博文发布订阅。然后,您的博客后端可以监控是否对博客帖子进行了任何更改,以及它们是否是向任何订阅的侦听器发布信息。听众将收到已发布的信息,并可以相应地更新或删除博客文章。

我不确定你使用的Comet解决方案是什么,如果使用Pusher完成,我可能会按照以下方式进行操作(希望你可以将想法转换为你自己的解决方案):

HTML

在每个博客帖子条目的HTML标记上都有唯一标识符,用于标识要订阅的频道。

<article data-entry-id="blog-post-1">
   Some blog post content
</article>
<!-- more blog posts -->

的JavaScript

由于您使用的是jQuery,因此可以在页面上找到所有博客文章:

var blogPosts = jQuery( 'article[data-entry-id]' );

您建立了与服务器的连接,在这种情况下是Pusher:

var pusher = new Pusher( 'app_key' );

然后订阅每个博客条目的频道:

var channels = {}; // lookup if required later
var channel;
blogPosts.each( function( i, el ) {
  el = jQuery( el );
  var blogId = el.attr( 'data-entry-id' );
  channel = pusher.subscribe( blogId );
  channel.bind( 'blog_entry_updated', handleUpdate );
  channel.bind( 'blog_entry_deleted', handleDelete );
  channels[ blogId ] = channel;
} );

现在已经订阅了每个博客帖子的频道,您需要编写代码来处理在这些频道上发生的事件(数据更新):

    更新博客文章时会调用
  • handleUpdate
  • 删除博客文章时会调用
  • handleDelete

我们假设您为blog_entry_updated发送的数据格式为:

{
  blogEntryId: 'an_id', // an ID that matches the data-entry-id attribute value
  html: '<!-- some HTML -->` // the HTML for the updated blog post
}

handleUpdate函数可以执行以下操作:

function handleUpdate( data ) {
  var blogId = data.blogEntryId;
  var el = jQuery( 'article[data-entry-id=' + blogId + ']' );
  el.html( data.html );
}

您可能还想添加某种效果来表明博客帖子已更新。

注意:如果您可以避免,我建议不要通过非常大的HTML发送。如果您可以通过增量发送(表示已更改的博客文章部分)可能更好。

handleDelete会做类似的事情:

function handleDelete( data ) {
  var blogId = data.blogEntryId;
  var el = jQuery( 'article[data-entry-id=' + blogId + ']' );
  el.slideUp( function() {
    el.remove(); // slide out of view then remove the element
  } );
}

PHP

在服务器上,您只需发布更改。

如果是更新,那么(使用Pusher PHP library)你会做类似的事情:

require( '../lib/Pusher.php' );
require( 'config.php' ); // general config. In this case it includes the Pusher config

// some code that handles the update, updates the DB etc.
// The result of which means we have a $blogEntryId value
// and $html for the updated content

// this data structure is converted to JSON to be consumed on the client
$data = array( 'blogEntryId' => $blogEntryId, 'html' => $html );

$pusher = new Pusher( APP_KEY, APP_SECRET, APP_ID );

// trigger the event on the appropriate channel, using the update event
$pusher->trigger( $blogEntryId, 'blog_entry_updated', $data );

这将导致$data被传递到客户端并调用handleUpdate函数。

删除的功能非常相似,只是我们没有要发送的HTML:

$data = array( 'blogEntryId' => $blogEntryId );

$pusher = new Pusher( APP_KEY, APP_SECRET, APP_ID );

$pusher->trigger( $blogEntryId, 'blog_entry_deleted', $data );

正如我上面提到的,希望您可以将类似于此解决方案的内容应用到您自己的Comet实现中。

相关问题