parsley/app/assets/javascripts/star_rating.js
2016-08-12 16:05:24 -05:00

76 lines
2.0 KiB
JavaScript

(function ($) {
var pluginName = "starRating";
var defaultOptions = {
starCount: 5
};
var methods = {
initialize: function(opts) {
return this.each(function() {
var options = _.extend({}, defaultOptions, opts);
var $input = $(this);
options.$input = $input;
var $widget = $("<span />").addClass("star-rating");
for (var x = 1; x <= options.starCount; x++) {
$widget.append(
$("<span />").addClass("star").data("rating", x)
);
}
$widget.data(pluginName + ".options", options);
$input.hide().after($widget);
privateMethods.updateStars($widget);
$widget.on("click." + pluginName, "span.star", function(e) {
var value = $(this).data("rating");
privateMethods.setValue($widget, value);
});
$input.on("change." + pluginName, function() {
privateMethods.updateStars($widget);
});
});
}
};
var privateMethods = {
updateStars: function($widget) {
var options = $widget.data(pluginName + ".options");
var value = parseInt(options.$input.val());
$widget.find(".star").each(function(idx, elem) {
var $star = $(elem);
$star.removeClass("empty full");
if ($star.data("rating") <= value) {
$star.addClass("full");
} else {
$star.addClass("empty");
}
});
},
setValue: function($widget, value) {
var options = $widget.data(pluginName + ".options");
options.$input.val(value);
privateMethods.updateStars($widget);
}
};
$.fn[pluginName] = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.initialize.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.' + pluginName);
}
};
})(jQuery);