Asked By: Anonymous
I am using Jquery rateIt plugin in my backbone project.
I am using its AJAX example part .
I could see images are loading no call going through and no response and some time get error like
“Uncaught TypeError: Object rateAnswer has no method ‘apply’ “
here is my JS
define(['jquery', 'underscore', 'backbone', 'text!tpl/questionnaire.html', 'Collection/cAppCollection', 'Models/mAppModel', 'jqueryRateIt'],
function($, _, Backbone, questionnaireTpl, appCollection, appModel, jqRateIt) {
var questionnaire = Backbone.View.extend({
el : '.row',
template : _.template(questionnaireTpl),
initialize : function(e) {
$('.hero-unit').css('display','none');
this.render(e);
},
//this renders my template
//on success of response , loads response than call rateit() function than bind rated and reset to function rateAnswer
//but here no call fo rateAnswer
render : function(e) {
var elem = this.$el,
temp = this.template,
appCollectObj = new appCollection();
appCollectObj.fetch({
data: $.param({subject: e.id}),
success: function(model, response) {
$(elem).html(temp({model:response}));
$('div.rateit').rateit();
$('#products .rateit').bind('rated reset', 'rateAnswer');
},
error: function() {
console.log('Failed to fetch!');
}
});
},
rateAnswer : function(){
var ri = $(this),
appCollectObj = new appCollection();
var value = ri.rateit('value');
var questionId = ri.data('productid');
appCollectObj.fetch({
data: $.param({questionId : questionId, value : value}),
success: function(model, response) {
$('#response').append('<li>' + data + '</li>');
},
error: function() {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
}
});
return questionnaire;
});
and HTML part is
<div id="products">
<ul>
<li>
RateIt: <div data-productid="<%= elem.id %>" class="rateit"></div>
</li>
</ul>
<ul id="response"></ul>
</div>
here the link to RateIt plugin example
Solution
Answered By: Anonymous
The error message is typical of an event binding incorrectly done… (trying to call apply on something that isn’t a function).
$('#products .rateit').bind('rated reset', 'rateAnswer');
I have never seen this syntax, where did you see in the documentation that you can give a string instead of the function parameter?
Here you want to bind to a function that is outside of your callback, so before the appCollectObj.fetch, add something like:
var thisView = this;
Then it should probably be:
$('#products .rateit').bind('rated reset', thisView.rateAnswer);
And you’ll probably have issues because this in the event handler won’t be working as you expect…so you can wrap your rateAnswer with $.proxy (or _.bindAll from _.underscore…):
$('#products .rateit').bind('rated reset', $.proxy(thisView.rateAnswer, thisView));