2014-01-23 209 views
0

如何從這個模型或集合中創建一個視圖和模板?我可以控制檯記錄我想要的數據。我被困在視圖和模板部分。謝謝。骨幹視圖和模板

var Weather = Backbone.Model.extend({ 
urlRoot: "http://api.openweathermap.org/data/2.5/weather?q=New%20York&mode=json&units=imperial", 
initialize: function (response) { 
     console.log(response.wind.speed);  
console.log(response.main.temp);  
console.log(response.name); 
console.log(response.main.temp_min); 
console.log(response.main.temp_max); 
//console.log(); 
return response; 
} 

}); 

var WeatherCollection = Backbone.Collection.extend({ 
model: Weather, 
url: 'http://api.openweathermap.org/data/2.5/weather?q=New%20York&mode=json&units=imperial', 
parse: function(response) { 
     console.log(response.wind.speed);  
console.log(response.main.temp);  
console.log(response.name); 
console.log(response.main.temp_min); 
console.log(response.main.temp_max); 
//console.log(); 
return response; 
} 
}); 

回答

0

我可能會做這樣的事情入手:

var WeatherItemView = Backbone.View.extend({ 
    template: _.template($('#weather-template').html()), 
    render: function() { 
    var content = this.template({ 
     weather: this.model 
    }); 

    this.$el.html(content); 
    return this; 
    } 
}); 

var WeatherListView = Backbone.View.extend({ 
    initialize: function() { 
    this.listenTo(this.collection, 'sync', this.render); 
    }, 
    render: function() { 
    this.collection.each(function (weather) { 
     var subView = new WeatherItemView({ 
     model: weather 
     }); 
     this.$el.append(subView.render().$el); 
    }, this); 

    return this; 
    } 
}); 

$(document).ready(function() { 
    var weathers = new WeatherCollection(); 
    weathers.fetch(); // assuming its accessing an api endpoint. 

    var weathersView = new WeatherListView({ 
    collection: weathers 
    }); 
    $('body').html(weathers.render().$el); 
}); 

<!-- template for one weather item view --> 
<script id='weather-template' type="text/template"> 
    <%= weather.escape('name') %> 
</script>