Exercise (05) - Solution

Implement exercise (04) as jQuery plugin. When done, all you should need to do is $('#rating').rating({url: 'http://path.to/script'}); to achieve the same result.

by bombo

HTML

<h3>Rating</h3>
<div id="rating">
</div>

CSS

h3 {
    margin: 8px 0;
    font-family: sans-serif;
    text-decoration: underline;
}

JavaScript

(function($) {

  $.fn.rating = function (options) {

    var $this = this,
        defaults =  {
                      clearFirst : false,
                      limit : 5
                    },
        opt = $.extend({}, defaults, options),
        clear = opt.clearFirst,
        $doRate = $('<div id="doRate" />'),
        $showNew = $('<a href="#">new</a>');

    $doRate.append('Please rate: ');

    for (var i = 1; i <= opt.limit; i++ ) {
      $doRate.append("<a href='#'>" + i + "</a> ");
    }

    $this.append($doRate);
    $this.append('<div id="result" />');

    $('#result').find('a').live('click', function () {
      $('#result').empty();
      $doRate.show();
    });

    $doRate.find('a').click(function (event) {
      event.preventDefault();
      
      $.ajax({
        url: opt.url,
        contentType: 'application/json',
        data: {rating: $(this).html(), clear: clear},
        dataType: 'jsonp',
        success: function (data) {
          $doRate.hide();
          $('#result').html(
            'Thanks for rating, current average: ' +
            data.average +
            ', number of votes: ' +
            data.count
          );
          $('#result').append('<br />').append($showNew);
        }
      });
      clear = false;
    });
    
    return $this;
  };
})(jQuery);

$(function () {
    $('#rating').rating({url: 'http://suppenzauber.com/rate/rate.php', clearFirst : true});
});