1
我是骨幹js的新手,在過去的幾天裏一直在研究這個項目 - 我試圖在骨幹視圖中做一個ajax get請求,但是堅持如何執行它。我在成功功能裏面做錯了什麼?使用ajax在BackBone中發出GET請求
查看:
var PictureView = Backbone.View.extend({
el: "#app",
template: _.template('<img src = <%=image%>/>')
events: {
//'
"click .button": this.render(); //?
},
render: function() {
var that = this; // to fix that `this` refers to in the callback
$.ajax({
var apiKey = "willreplacetomykey";
url: "https://api.flickr.com/services/rest/?jsoncallback=?",
method: 'flickr.photos.search',
api_key: apiKey,
format: 'json',
nojsoncallback: 1,
per_page: 1
success: function(result) {
//do the setting and rendering.
this.model.set({
image: result
})
return this.$el.html(this.template((this.model.attributes));
}
});
});
}
})
Model:
var Picture = Backbone.Model.extend({
defaults: {
image: ""
},
initialize: function() {
},
addImage: function() {
//?
},
});
'this.model'的作用域爲成功函數,也許將其改爲'that.model'來解決您的範圍問題可能會解決它嗎? –
有很多事情可以幫助你在這裏,但我認爲主要的問題是你沒有利用它的工具來分離問題。您應該嘗試從表示層分離數據層。目前,如果您想爲模型使用不同的視圖,則必須再次編寫ajax調用。考慮文檔:模型是任何JavaScript應用程序的核心,它包含交互式數據以及圍繞它的大部分邏輯:轉換,驗證,計算屬性和訪問控制。 – mtl