javascript - Backbone.js 的延迟 JSON 响应

标签 javascript json backbone.js

我正在使用backbone.js 开发我的第一个项目。它应该是 Play 的前端!具有 JSON 接口(interface)的应用程序。这是我的 JS 代码的一部分

var api = 'http://localhost:9001/api'

// Models
var Node = Backbone.Model.extend();

// Collections
var Nodes = Backbone.Collection.extend({
  model: Nodes,
  url: api + '/nodes',
});

// Views NODE
var NodeView = Backbone.View.extend({
  el: $("#son_node_elements"),
  render: function(){
    var source = $("#son_node_item_templ").html();
    var template = Handlebars.compile(source);
    $(this.el).append(template(this.model.toJSON()));
    return this;
  }
});

var NodeListView = Backbone.View.extend({

  initialize: function(){
    _.bindAll(this, "render");
    this.collection = new Nodes();
    this.collection.bind("change",this.render);
    this.collection.fetch();
    this.render();
  },

  render: function(){
    _(this.collection.models).each(function(item){ 
      var nodeView = new NodeView({model: item});
      $(this.el).append(nodeView.render().el);
    }, this);   
  }
});

Nodes = new NodeListView({el:$('#son_nodes')});

我的问题是,当调用 this.render() 时,this.collection.fetch() 仍未完成,并且 this.collection code> 不包含任何要渲染的内容。当我在 this.render() 处设置断点(例如使用 firebug)时,一切正常,因此不会立即调用 this.render() 。当我访问本地 JSON 文件而不是我的应用程序的 api 时,我得到完全相同的结果。有什么建议如何处理这个问题吗?

最佳答案

Fetch 也可以从外部 View 调用,因此让 View 监听它:

this.collection.bind("reset",this.render);

每次调用 this.collection.fetch();  时都会触发重置事件

最后,跳过this.render();不要自己调用它,因为重置事件处理程序会为您执行此操作。

关于javascript - Backbone.js 的延迟 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510845/

相关文章:

javascript - 为禁用的输入框添加 onclick

javascript - JavaScript 中相同的输入,不同的输出?

javascript - 通过 jQuery 在悬停时向 setInterval 添加停止

android - 使用 Android ComplexPreferences (JSON) 保存 Bundle

backbone.js - 如何使用 underscore.js 的 groupBy 按字符串属性对 Backbone.js 中的集合进行分组?

javascript - HTML中的属性和属性有什么区别?

java - 使用 Jackson 反序列化时禁用标量到字符串的转换

php - 从 CURL JSON 响应 php 数组中获取特定值

javascript - Backbone : Correct way of passing 'this' reference to anon functions in success/error callbacks

将历史状态替换为同一路径后,Javascript 使用哈希重定向