【问题标题】:Backbone Collection wont render outside of fetchBackbone Collection 不会在 fetch 之外呈现
【发布时间】:2014-03-19 20:20:02
【问题描述】:

问题:如果在获取集合时在成功回调之外调用渲染方法,我的集合无法呈现到页面。

我有一个基本的骨干集合,在它从我的服务器获取一些 json 后,我试图将它呈现给我的应用程序。在学习了一堆教程之后,我希望它会像这样工作:

var restaurants = new RestaurantsCollection();
var restaurantsView = new RestaurantsView({collection: restaurants});
restaurants.fetch():
$(curate.targets.restaurantApp).append(restaurantsView.render().el);

集合成功获取 json,但从未附加到页面。

或者,如果我附加在fetch() 的成功回调中,它会附加到页面罚款。像这样:

var restaurants = new RestaurantsCollection();
var restaurantsView = new RestaurantsView({collection: restaurants});
restaurants.fetch({
    success: function(collection){
        console.log(collection);
        $(curate.targets.restaurantApp).append(restaurantsView.render().$el);


    },
    error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
        console.log(jqXHR);
    }
});

餐厅视图:

var RestaurantsView = Backbone.View.extend({
    el: $(curate.targets.restaurantList),
    initialize: function(){
      this.collection.fetch();
      this.listenTo(this.collection, 'reset', this.render, this);
    },
    render: function(){
      this.addAll();
      return this;
    },
    addAll: function(){
      this.collection.forEach(this.addOne, this);
    },
    addOne: function(RestaurantModel){
      var restaurantView = new RestaurantModelView({model: RestaurantModel});
      this.$el.append(restaurantView.render().el);
    }
});

是否需要在fetch()的成功回调中追加渲染和追加视图或者有没有更好的方法?

【问题讨论】:

  • 您需要使用回调,因为 fetch 是异步的。或者,您可以将集合的“添加”事件绑定到您的视图
  • @Gohn67 我知道 fetch 是异步的,但必须有一种更简洁的方法来创建我的集合并呈现我的视图,对吗?还是这样
  • 您实际上在哪里“渲染” html?另外,我认为“同步”是更好听的事件。仅当您调用“reset()”时才会触发“reset”事件 - 我在您的代码中也没有看到。我在看1.0.0版本的源代码。
  • @anAgent 你的权利,将事件更改为sync 让我在获取时呈现集合,就像我想要做的那样。休息只适用于this.collection.fetch({reset: true});。如果你用这个更新你的答案,我会接受它。
  • 太好了,很高兴听到!我已经更新了我的答案。

标签: javascript backbone.js


【解决方案1】:

你应该能够在你的集合上绑定一个触发你视图渲染的事件——就像这样:

这假定您的 RestaurantView initialize 函数中的代码。

this.collection.on('change', this.render);

此外,您要查找的事件将是“sync”而不是“reset”。 Backbone 1.0.0 中的当前源代码将在获取后触发 sync 事件。

注意:如果服务器没有返回任何数据,则不会触发“同步”。

【讨论】:

  • 我在初始化函数中使用this.listenTo(this.collection, 'reset', this.render, this);。关于为什么在成功后可能不会调用渲染函数的任何其他想法?
  • 此外,'reset' 只会在您使用 collection.fetch({reset: true}); 时触发。
【解决方案2】:

Fetch 是通过 ajax 从你的服务器获取数据,你需要一个回调函数在 .fetch 之后

【讨论】:

    【解决方案3】:

    尝试重新排序行。通常所有要回调的事件都会在调用fetch之前先注册。

    initialize: function(){
      this.listenTo(this.collection, 'reset', this.render);
      this.collection.fetch();
    },
    

    【讨论】:

      猜你喜欢
      • 2012-11-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2017-12-05
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多