我是新來的主幹,我似乎無法顯示集合中的數據。請指出不正確的部分。主幹:從服務器獲取的數據不會顯示在視圖上
考慮這些JS代碼:
App.ProvidersView = Backbone.View.extend({
id: "Providers",
template: "#-providers-template",
render: function() {
var html = $(this.template).tmpl();
$(this.el).html(html).addClass('container-fluid');
this.collection.each(this.renderProvider);
},
initialize: function() {
_.bindAll(this, "renderProvider");
},
renderProvider: function(Provider){
var ProviderView = new App.ProviderView({
model: Provider
});
ProviderView.render(Provider);
$(this.el).append(ProviderView.el);
}
});
App.ProviderView = Backbone.View.extend({
id: "Provider",
template: "#-provider-template",
initialize: function(){
this.template = $(this.template);
},
render: function(){
var html = this.template.tmpl(this.model.toJSON());
$(this.el).html(html);
}
});
App.Provider = Backbone.Model.extend();
App.ProviderCollection = Backbone.Collection.extend({
url: "php/Provider.php",
model: App.Provider
});
App.addInitializer(function() {
var providers = new App.ProviderCollection();
providers.fetch({success: function() {
console.log(Providers.models);
}});
var provider = new App.Provider();
var providersView = new App.ProvidersView({
model: Provider,
collection: Providers
});
providersView.render();
$("#main").html(providersView.el);
$("#providers-list").html(provider.el);
});
App.bind('initialize:after', function() {
Backbone.history.start();
});
$(function() {
App.start();
});
模板:
<script type="text/x-jquery-tmpl" id="content-providers-template">
<div class="row-fluid">
<div class="span12">
<h5>Content Providers</h5>
</div>
</div>
<div id="content-providers-list"></div>
</script>
<script type="text/x-jquery-tmpl" id="content-provider-template">
<div class="row-fluid">
<div class="span12">
<div class="panel">
<h2 class="toggle"><i class="icon-chevron-down icon-white pull-right"></i>${name}</h2>
</div>
</div>
</div>
</script>
依賴關係:
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.tmpl.min.js"></script>
<script type="text/javascript" src="scripts/json2.js"></script>
<script type="text/javascript" src="scripts/underscore.js"></script>
<script type="text/javascript" src="scripts/backbone.js"></script>
<script type="text/javascript" src="scripts/backbone.marionette.js"></script>
此外,如果你可以分享真正好的資源,學習骨幹,我會強烈欣賞它。
您設置爲視圖的'el'地方? 'id'(至少在vanilla backbone.js中,不知道有關木偶)是模型的一個屬性,而不是視圖。 – Jack 2013-03-11 01:55:49
對不起,不確定。但是,當您對json數據進行硬編碼並將其傳遞給集合實例時,代碼工作正常。我的問題是如何通過集合獲取從服務器顯示數據。它不工作。 – user1966211 2013-03-11 02:07:01
您是否從服務器獲取數據?要記住的一個潛在的* gotcha *是fetch是異步的,因此在獲取數據之前可能會觸發render方法。 – Jack 2013-03-11 02:10:20