骨干视图和模板

时间:2014-01-23 01:14:56

标签: backbone.js view

如何从此模型或集合创建视图和模板?我可以控制记录我想要的数据。我被困在视图和模板部分。感谢。

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;
 }
 });

1 个答案:

答案 0 :(得分: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>