渲染CollectionView

时间:2013-08-13 04:34:24

标签: backbone.js

这个问题已被详细询问,但我似乎无法得到适合我的代码的任何示例。我的模型和集合填充,我从控制台输出,但可以;似乎让AppView.render做任何其他事情,然后打印'渲染视图......'

var Foodtruck = Backbone.Model.extend({
  defaults: {
    'name': '',
    'twitter': '',
    'categories': [],
    'coordinates': {
      'latitude': 0,
      'longitude': 0
    }
  }
});

var FoodTruckCollection = Backbone.Collection.extend({
  model: Foodtruck,
  url: 'http://api.mobilefeast.info/foodtrucks',
  initialize: function(){
        this.bind("render", function( model ){
            alert("hey");
            view.render( model );
        })
  },
  parse: function(response) {
    return response;
  },
  getData: function(){
    var that = this;
    that.fetch(
    {
        success: function () {
          console.log('Data is fetched');
        },
        error: function() {
          console.log('Failed to fetch!');
        }
   });
  }
});

var AppView = Backbone.View.extend({
    el:$('#container'),

    initialize: function(){
        console.log('initialize AppView');
        this.foodtrucks = new FoodTruckCollection();
        this.foodtrucks.getData();
    },
    render: function(){
        console.log('rendering view...');
        this.foodtrucks.each(function(model){
          console.log(JSON.stringify(model));
        });
    }
});

new AppView().render();

尝试了这个问题:fetch after render

但没有运气

更新

var AppView = Backbone.View.extend({
    el:$('#container'),
    initialize: function(){
        console.log('Initialize');
        this.foodtrucks = new FoodTruckCollection();
        this.foodtrucks.fetch(
        {
          success: function () {
            console.log('Data is fetched');
          },
          error: function() {
            console.log('Failed to fetch!');
          }
        });
        this.listenTo(this.foodtrucks, 'sync', this.render);
    },
    render: function(){
      console.log('Rendering');
      this.foodtrucks.each(function(model){
        console.log(model.toJSON().name);
      });
    }
});

0 个答案:

没有答案