我是骨干js的新手,并且在过去的几天里一直致力于这个项目 - 我试图在骨干视图中制作ajax 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() {
//?
},
});
答案 0 :(得分:2)
目前,您的成功功能已失去您正在寻找的this
上下文,并且您无法从成功回调中返回任何内容。修复this
绑定的最简单方法是执行函数绑定:
success: function(result) {
this.model.set({
image: result
})
this.$el.html(this.template(this.model.toJSON()));
}.bind(this)
或者您可以使用您创建的that
变量:
success: function(result) {
that.model.set({
image: result
})
that.$el.html(that.template(that.model.toJSON()));
}
或者你甚至可以让成功回调触发视图/模型上的另一个函数,并将结果传递给它,如果你需要做一些更复杂的事情:
success: function(result) {
this.model.setResults(results);
}
在模型上:
setResults: function(results) {
// do things with results
}