I'm having a problem with using this
in js. I have a function that uses this
like this:
var refreshRequesterStar = function() {
$(".rating").raty({
score: function() { return $(this).attr('data-rating'); },
readOnly: function() { return $(this).attr('data-readonly'); },
halfShow: true
});
};
The rating div is as follow:
<div class="rating" data-readonly="false" data-rating="3.0" style="cursor: default; width: 100px;" title="not rated yet">
<div class="rating" data-readonly="false" data-rating="0.0" style="cursor: default; width: 100px;" title="not rated yet">
This is called by this function:
$("body").ajaxComplete(function(){
refreshRequesterStar();
$(".time_to_expire").each(function(){
setCountDown(this);
})
$('select').chosen();
});
I was able to set the score value but I cannot set the readOnly value. When I debugged using firebug, I found that the first this pointed to the div but the second this pointed to window. Where I have been wrong? Note: I don't know much about JavaScript.
More info: I was using raty http://www.wbotelhos.com/raty with rails.
The documentation and examples indicate that the parameter score
and readOnly
are supposed to be numeric and boolean, not callback functions. You might want to re-write your code this:
$(".rating").each(function() {
// inside the function, this refers to the .rating element being iterated
$(this).raty({
score: parseFloat($(this).attr('data-rating')), // see note #1
readOnly: $(this).attr('data-readonly') == "true", // see note #2
halfShow: true
});
});
.attr()
returns a string; parseFloat()
function is used to convert a string e.g. "2.5"
into the number 2.5
== "true"
returns boolean true if the attribute value is equal to "true"
; returns false in all other casesRef: