Its a very basic java-script with modular structure, basically what I'm trying to do is , requesting a random quote via an API, printing them on the HTML page via Mustache.js. Earlier without using the modular structure way, I managed to accomplish this task, but I wanted to try the modular way too.
The problem i'm facing now is that whenever i try to render my data (i.e quote + author) , I recieve an error on my console that the function is not defined.
Please check my code ~
(function (){
var quoting ={
quotei : [],
template : $("#quoteTemplate").html(),
init: function (){
this.cacheDom();
this.bindEvents();
this.createQuote();
this.recieve();
this.renderx();
},
cacheDom: function(){
this.$el = $('#quotez');
this.$button = this.$el.find('button');
this.$template = this.$el.find('#quoteTemplate').html();
},
bindEvents: function(){
this.$button.on('click',this.createQuote.bind(this));
},
renderx: function(data){
this.$el.html(Mustache.render(this.template,data));
},
createQuote: function(){
$.ajax({
url:'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type:'GET',
data:{},
dataType:'json',
success : function(data){;
this.render(data)
},
beforeSend: function(xhr){
xhr.setRequestHeader("X-Mashape-Authorization","cvkQkHJurZmshuIhXxwXzIjBchHVp1yk0rDjsnNambAJ9duu7v");
}
});
},
};
quoting.init();
})()
Please help me out and pardon for any mistakes , as this is my first time posting on StackOverflow.
Here is the refactored code
Working Demo: here Output: [object Object] { author: "Martin Luther King Jr.", category: "Famous", quote: "In the End, we will remember not the words of our enemies, but the silence of our friends." }
Code:
(function ($) {
function quoting() {
this.quotei = [];
this.template = $("#quoteTemplate").html();
this.init();
}
quoting.prototype = {
init: function () {
this.cacheDom();
this.bindEvents();
this.createQuote();
//this.recieve();
//this.renderx();
},
cacheDom: function(){
this.$el = $('#quotez');
this.$button = this.$el.find('button');
this.$template = this.$el.find('#quoteTemplate').html();
},
bindEvents: function(){
this.$button.on('click', this.createQuote.bind(this));
},
renderx: function(data) {
console.log(data);
//this.$el.html(Mustache.render(this.template,data));
},
createQuote: function(){
var self = this;
$.ajax({
url:'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type: 'GET',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization","cvkQkHJurZmshuIhXxwXzIjBchHVp1yk0rDjsnNambAJ9duu7v");
}
}).done(function(data) {
self.renderx(data);
})
}
};
var myQuote = new quoting();
})(window.jQuery);