2

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

但后来我们意识到,如果用户编辑或删除了他们自己的博客文章,那篇文章位于页面的中间,该怎么办?我们将如何更新它?

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

4

1 回答 1

3

由于您使用的是Comet解决方案,因此您可能遵循某种发布-订阅模式

从那里你有几种方法来实现你正在寻找的东西。一种解决方案是为页面上可见的每篇博客文章订阅。然后,您的博客后端可以监控是否对博客文章进行了任何更改,以及它们是否将信息发布给任何订阅的听众。听众将收到发布的信息,并可以相应地更新或删除博客文章。

我不确定您使用的是什么 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 块。如果您可以通过 delta 发送(表明博客文章中已更改的部分),那可能会更好。

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 库)你会做类似的事情:

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 实现中。

于 2013-02-20T10:10:03.857 回答