0
我想用backbone.js和mustache來使用Django和tastypie。我已經建立了一個例子來研究這些。如果使用下面的代碼,我得到用戶的結果加倍:Backbone.js提取倍增的結果
- -Id用戶名
- -1 YOL
- -2達達
- -1 YOL
- -2達達
---我的代碼---
// I think this tastypie adjustment is not related with the problem but i want you to see the //whole code
window.TastypieModel = Backbone.Model.extend({
base_url: function() {
var temp_url = Backbone.Model.prototype.url.call(this);
return (temp_url.charAt(temp_url.length - 1) == '/' ? temp_url : temp_url+'/');
},
url: function() {
return this.base_url();
}
});
window.TastypieCollection = Backbone.Collection.extend({
parse: function(response) {
this.recent_meta = response.meta || {};
return response.objects || response;
}
});
(function($){
// MODELS-COLLECTIOS
//USERS
var User = TastypieModel.extend({
url: USERS_API
});
var Users = TastypieCollection.extend({
model: User,
url:USERS_API
});
//VIEWS
var UsersView = Backbone.View.extend({
render: function(){
// template with ICanHaz.js (ich)
this.el = ich.userRowTpl(this.model.toJSON());
return this;
}
});
//main app
var AppView = Backbone.View.extend({
tagName: 'tbody',
initialize: function() {
this.users = new Users();
this.users.bind('all', this.render, this);
this.users.fetch();
},
render: function() {
// template with ICanHaz.js (ich)
this.users.each(function (user) {
$(this.el).append(new UsersView({model: user}).render().el);
}, this);
return this;
}
});
var app = new AppView();
$('#app').append(app.render().el);
})(jQuery);
謝謝。它解決了雙倍的問題。但是我在** AppView的render **函數中做了一個小測試,並寫了一個'alert('test')'函數。它會調用alert兩次,這意味着它會渲染兩次,這是預期的行爲嗎? – ratata 2013-03-11 14:51:39
是的,因爲你還在調用渲染兩次,第一個'$('#app')。append(app.render()。el);'第二個'this.users.bind('reset',this .render,this);'這是預期的方式,因爲在第一次調用中,集合尚未被提取,因此它正在渲染集合模型的集合是綁定到重置事件的集合,在集合之後觸發它被提取。 – Puigcerber 2013-03-11 15:01:34