ajax - 主干 View : Wait until collection fetched

标签 ajax backbone.js underscore.js

我想知道如何告诉主干等待我的集合获取模型然后渲染下划线位。

在控制台中从下划线模板返回一个错误,指出缺少字段。当我 console.log(this.collection.toJSON()) 它不显示任何数据。所以我假设,在获取数据之前呈现 View 。我如何告诉 View 等待它被获取?

///////看法////////

define([
  'jquery',
  'underscore',
  'backbone',
  'collections/mitarbeiter',
  'text!/aquilamus/templates/mitarbeiter/mitarbeiter.html'
], function($, _, Backbone, MitarbeiterCollection, MitarbeiterTemplate){



 var MitarbeiterListView = Backbone.View.extend({
    el: $("#container"),
    initialize: function(){
      this.collection = new MitarbeiterCollection;
      this.collection.fetch();
      var newtemplate = MitarbeiterTemplate;
      this.template = _.template($(newtemplate).html());
    },
    render: function(){
      var renderedContent = this.template(this.collection.toJSON());

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


  });
  // Our module now returns our view
  return MitarbeiterListView;
});

最佳答案

使用 reset像其他人建议的作品一样,但这里有一个替代方案。

define([
  'jquery',
  'underscore',
  'backbone',
  'collections/mitarbeiter',
  'text!/aquilamus/templates/mitarbeiter/mitarbeiter.html'
], function($, _, Backbone, MitarbeiterCollection, MitarbeiterTemplate){

 var MitarbeiterListView = Backbone.View.extend({
    el: $("#container"),
    initialize: function(){
      this.collection = new MitarbeiterCollection;

      var newtemplate = MitarbeiterTemplate;
      this.template = _.template($(newtemplate).html());
    },
    render: function(){
      var self = this;

      // show some loading message
      this.$el.html('Loading');

      // fetch, when that is done, replace 'Loading' with content
      this.collection.fetch().done(function(){
          var renderedContent = self.template(self.collection.toJSON());
          self.$el.html(renderedContent);
      });
      return this;
    }

  });
  // Our module now returns our view
  return MitarbeiterListView;
});

另一种选择是做一些与此非常相似的事情,除了使用 the success callback function您可以将其放入获取选项中。

关于ajax - 主干 View : Wait until collection fetched,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15576578/

相关文章:

javascript - Form_Open 始终提交 - 通过 Ajax 提交 - CodeIgniter

javascript - 带有附加信息的文件的上传处理程序

javascript - Backbone Event 触发不同 View 之间的协调

Javascript按值将数组转换为分组对象

JavaScript。像 SQL 一样连接 2 组对象的最佳方法?

javascript - 如何在每个调用堆栈中只调用一次函数?

javascript - 如果数据库中存在输入,则重定向到 URL

php - 我没有看到ajax的最后一次调用

javascript - 返回 $.extend 并将其放在 Backbone 中

javascript - backbone.js - View 中的 View 和管理事件