2015-10-15 8 views

回答

0

我使用子視圖實現了2調用主視圖。那變得更復雜了。但是這應該讓你開始。

這些是獲取數據的主要2個集合。如果您想進一步細分(取決於需求),您可以創建一個Model,然後使用model: CityModel(在本例中)將其分配給集合。

var Cities = Backbone.Collection.extend({ 
    url: 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=me', 
    parse: function(response) { 
     return response.geonames; 
    } 
}); 

var Earthquakes = Backbone.Collection.extend({ 
    url: 'http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=me', 
    parse: function(response) { 
     return response.earthquakes; 
    } 
}); 

然後子視圖,標準:在這裏你可以創建每個事件。

var EarthquakeView = Backbone.View.extend({ 
    tagName: 'li', 
    template: _.template('<strong><%=eqid%></strong> <%=lng%> <%=lat%> magnitude: <%=magnitude%>'), 
    render: function() { 
     this.$el.html(this.template(this.model.toJSON())) 
     return this; 
    } 
}); 

注意這裏你可以extend一個視圖,以便您不必重複自己。

var CityView = EarthquakeView.extend({ 
    template: _.template('<strong><%=toponymName%></strong> <%=lng%> <%=lat%>') 
}); 

主要看..

var View = Backbone.View.extend({ 
    initialize: function(opt) { 
     // attach to the main body 
     $(opt['main']).append(this.el) 

     this.earthquakesEl = $('<ol>'); 
     this.earthquakes = new Earthquakes() 
     this.earthquakes.on('sync', _.partial(this.renderList, EarthquakeView, this.earthquakesEl), this); 
     this.earthquakes.fetch() 

     this.citiesEl = $('<ol>'); 
     this.cities = new Cities() 
     this.cities.on('sync', _.partial(this.renderList, CityView, this.citiesEl), this); 
     this.cities.fetch() 

     // initialize the element 
     this.render(); 
    }, 
    renderList: function(view, el, collection) { 
     collection.forEach(function(model) { 
      el.append(new view({model: model}).render().el) 
     }); 
    }, 
    render: function() { 
     this.$el.append(this.earthquakesEl); 
     this.$el.append(this.citiesEl); 

     return this; 
    } 
}); 

new View({ main: $('body') }); 

http://jsfiddle.net/u9y574y8/2/

但是也有一些獨立製作2個集通話,並有2個聽衆,等待它們完成,然後將其放置在主視圖。如果您有任何問題,請告訴我。我認爲它非常簡單。

+0

感謝您的詳細解釋。我今天做了一些研究,並使用jQuery $。當結合兩個響應 – rip999

+0

我不知道你的確切用例,但99%的時間,當我需要異步加載的東西,我從來沒有試圖將它們結合起來,你只是要惹惱用戶。最好只裝入(如果可能)多少塊碎片並在它們完成時縫合它們,而不是等到一切都完成後縫合它們。另一方面,如果你可以提供一些關於你實際在做什麼的代碼,我可以提供更多幫助。 –

相關問題