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

时间:2013-09-13 20:29:24

标签: javascript json backbone.js

好的,超级基本的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不是函数”

谢谢!

3 个答案:

答案 0 :(得分:5)

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

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

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

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

与他们一起玩,看看是否无法修复它。

答案 1 :(得分:3)

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

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

无论如何使用onlistenTo都是更好的aproaches然后绑定。

答案 2 :(得分:1)

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

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服务时,这是我的最小骨干骨架。我没有在本地测试,但这样代码应该工作。