Simple Blog with jQuery, validation and editing

This example is an extenstion of the htmljQueryValBlog where we add the in place editing capabilities to the title and content.

HTML providers the contenteditable attribute that turns any tag into an editable element by the user. Now supported on iOS 5 and Android Browser 3.0, it allows in place editing on mobile pages.

In the example, we add the contenteditable attribute to the title and content fields of the blog main page

views/index.haml
%ul(data-role = "listview")
  - $articles.each_with_index do |a, i|
    %li
      %p.ui-li-aside
        =a[:timestamp]
      %h3(contenteditable="true" data-name="title" data-id='#{i}') 
        =a[:title]
      %p
        %strong
          =a[:email]
      %p(contenteditable="true" data-name="content" data-id='#{i}')
        =a[:content]

On the client we add the functionality for detecting when the content is changed by the user and we post the updates to the server.

JS
$("[contenteditable]").focus(function() {
  var $this = $(this);
  $this.data('before', $this.html());
  return $this;          
});
$("[contenteditable]").live('blur', function() {
    var $this = $(this);
    if ($this.data('before') !== $this.html()) {
        $this.data('before', $this.html());
        $this.trigger('change');
        //alert($this.attr('data-id'));
        var msg = {};
        msg['id'] = $this.attr('data-id');
        msg[$this.attr('data-name')] = $this.html();
        $.post('/update', msg);
    }
    return $this;
});       

On the server side we add the method for updating the entry

server.rb
post '/update' do
  #Symbolize the params keys
  article = params.inject({}) { |h,(k,v)| h[k.to_sym] = v; h }

  #Update the timestamp
  article[:timestamp] = timestamp
  
  #Replace the entry in the list of articles
  $articles[article[:id].to_i].merge!(article)

  puts $articles
end

You can try this example by starting the server and visiting the page http://localhost:4567 in your browser

terminal
ruby server.rb