モジュラー構造の非常に基本的なJavaスクリプトで、基本的にAPIを使ってランダムな見積もりを要求し、Mustache.js経由でHTMLページに出力します。以前はモジュラー構造の方法を使用せずにこの作業を達成しましたが、私はモジュール方式でも試してみたかったのです。モジュール式js構造体でajax呼び出しを介してデータを受け取る方法は?
私が直面している問題は、データ(つまり引用+作成者)をレンダリングしようとするたびに、その機能が定義されていないというエラーがコンソールに表示されることです。
私のコードを確認してください〜
(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();
})()
これはStackOverflowの上で投稿私の最初の時間であるように、私を助け、間違いのためご容赦ください。 here 出力: [オブジェクトのオブジェクト] { 著者: "マーティン・ルーサー・キング・ジュニア"、 カテゴリ:、 "有名な" 引用:「ここに
2つのことをチェックアウトする - あなたの成功の機能であなたを呼び出す 'this.render()'が、それは 'その前に()' RenderX提供を綴られています...おそらく間違いでしょうか?また、 'success'ハンドラーの中で' this'は 'xhr'オブジェクトを指していて、あなたの外部関数ではないことに注意してください。あなたは適切な 'this'をバインドして動作させる必要があります。 – mherzig