這裏是我的代碼:如何渲染模型,我得到的AJAX數據
型號:
var app = app || {};
app.Film = Backbone.Model.extend({
defaults: {
poster: 'http://placehold.it/320x150',
title: 'No name',
genre: 'Unknown',
runtime: 'Unknown',
imdbRating: 0
},
parse: function(response) {
response.id = response._id;
return response;
}
});
收藏:
var app = app || {};
app.Films = Backbone.Collection.extend({
model: app.Film,
url: '/api/films'
});
瀏覽次數: 型號:
var app = app || {};
app.FilmView = Backbone.View.extend({
tagName: 'div',
className: 'filmContainer',
events: {
},
initialize : function() {
this.template= _.template($('#filmTemplate').html());
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
收藏品:
ar app = app || {};
var global = 'global';
app.FilmsView = Backbone.View.extend({
el: '#films',
events:{
},
initialize: function() {
this.collection = new app.Films();
this.collection.fetch();
this.render();
this.listenTo(this.collection, 'add', this.renderFilm);
this.listenTo(this.collection, 'reset', this.render);
this.listenTo(Backbone.Events, 'findFilm', this.findFilm);
},
render: function() {
this.collection.each(function(item) {
this.renderFilm(item);
}, this);
console.log('render');
},
renderFilm: function(item) {
var filmView = new app.FilmView({
model: item
})
this.$el.append(filmView.render().el);
console.log('renderFilm');
},
findFilm: function() {
console.log('findFilm');
$.ajax({
type: "POST",
url: "/film/find",
data: {
name: "Gotham"
},
success: function(data){
app.FilmsView.collection = new app.Films();
app.FilmsView.collection.add (data[0]);
console.log(app.FilmsView.collection)
}
});
}
});
理念我的問題是 - 我必須從現場得到的字符串,並將其用於在DB的電影搜索。 「/ film/find」請求用包含模型字段的對象響應我。我需要一些方法來在頁面中顯示此模型。正如我在初始化時使用fetch()方法:頁面顯示所有數據庫模型。所以我需要清晰的收集並且只顯示我從服務器獲得的一個模型。 this.collecion.reset()不起作用,不會觸發render()事件。
Indetesting認爲:app.FilmsView.collection returnt在渲染後返回「undefined」,所以我需要爲AJAX響應創建新的集合。
您必須從什麼領域什麼字符串? – AdamJeffers
電影名稱,名稱:「Gotham」 - 測試變量。 我沒有與數據獲取obj probs,問題是顯示此數據作爲收集模型。 –