繁体   English   中英

Backbone.js:在模型中渲染json数据

[英]Backbone.js: Rendering json data in a model

好的,超级基本的Backbone问题 - 我一直在寻找这个问题,但是尽管有很多类似的问题,我还是太慢了。 请放心,我感到很惭愧。

无论如何,足够的自我鞭 - - 这为什么不渲染?

var app = app || {};

app.Option = Backbone.Model.extend({
url: 'http://localhost:4711/api'

//This url contains the following JSON: {"title": "Blahblah", "author": "Luke Skywalker"};  
});

 app.View = Backbone.View.extend({

el: 'body',

initialize: function(){
    this.model.fetch();
    this.model.bind('change', this.render(), this);
},

render: function(){
    this.$el.html(this.model.get('title'));
    return this;
}

});


$(function() {

 var option = new app.Option();
    this.homeView = new app.View({   //Tried changing this to a standard var declaration but didn't work
      model: option
    });
    this.homeView.render();
});

所以我期待在屏幕上看到JSON“Blahblah”,但我什么都没看到。 JSON正在被正确获取(我可以在firebug控制台中看到成功的GET请求),我想我确保在尝试渲染数据之前获取数据...

那有什么不对? 控制台给我这个错误:“TypeError :(中间值).callback.call不是一个函数”

谢谢!

有一点是你在事件绑定中立即调用this.render()而不是仅仅绑定回调。 这样做(使用listenTo获得最佳实践):

initialize: function(){
    this.listenTo(this.model, 'change', this.render);
    this.model.fetch();
}

该模型可能实际上没有变化吗? 您可能尝试绑定到sync而不是change以查看是否有效。

你也渲染了两次。 一旦直接使用this.homeView.render() ,一次通过事件处理程序。 如果您真的想要在initialize保持模型提取并绑定到更改事件,则不需要直接渲染。

与那些玩,看看是否不解决它。

只需在绑定时从render方法中删除括号:

this.model.bind('change', this.render, this);

同时使用onlistenTo是一种更好的方法然后bind

我将通过以下方式构建骨干骨架:

var app = app || {};

app.Option.Model = Backbone.Model.extend({});

app.Option.Collection = Backbone.Collection.extend({       
   model : app.Option.Model,

   fetch : function(options) {     
       Backbone.Collection.prototype.fetch.call(this, options);
   },

   url : function() {
       return 'http://localhost:4711/api';
   },

   parse: function(response) { // this is the ajax call
      console.log(response);
   }
});

然后在View中初始化时调用fetch方法:

app.Option.View = Backbone.View.extend({
    collection : app.Option.Collection,

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

    render : {
       var results = this.collection.toJSON(); 
       console.log(results);
    }
});

当我需要调用web服务时,这是我最小的骨干骨架。 我没有在本地测试,但这样代码应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM