Created
July 7, 2013 11:17
-
-
Save danielmackay/5943165 to your computer and use it in GitHub Desktop.
Knockout startbinding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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