Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Created July 7, 2013 11:17
Show Gist options
  • Save danielmackay/5943165 to your computer and use it in GitHub Desktop.
Save danielmackay/5943165 to your computer and use it in GitHub Desktop.
Knockout startbinding.
ko.bindingHandlers.starRating = {
init: function(element, valueAccessor) {
$(element).addClass("starRating");
for (var i = 0; i < 5; i++)
$("<span>").appendTo(element);
// Handle mouse events on the stars
$("span", element).each(function(index) {
$(this).hover(
function() { $(this).prevAll().add(this).addClass("hoverChosen") },
function() { $(this).prevAll().add(this).removeClass("hoverChosen") }
).click(function() {
var observable = valueAccessor(); // Get the associated observable
observable(index+1); // Write the new rating to it
});
});
},
update: function(element, valueAccessor) {
// Give the first x stars the "chosen" class, where x <= rating
var observable = valueAccessor();
$("span", element).each(function(index) {
$(this).toggleClass("chosen", index < observable());
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment