1

i use fetch from backbone.js to load a json model but success will not hit.

var DialogModel = Backbone.Model.extend({
    url : function() {
        return '/messages/getDialog';
    },
    parse : function(res) { 
        return res.dialog;
    }
});

var DialogView = Backbone.View.extend({
    el: $("#page"),
    initialize: function() {
        var onDataHandler = function() {
            this.render();
        };
        this.model = new DialogModel();
        this.model.fetch({ success : onDataHandler});
      },
    render: function(){
        var data = {
                dialogModel : this.model
              };
        var form = new Backbone.Form({
             model: data
        });
        $(this.el).html(form.render().el);
    }
});

What happens now: DialogView initialize is called. this.model.fetch is called but the onDataHandler function will not be hit if success. /messages/getDialog throws a json file back. The json file is loading well as i can see in the network browser.

Thanks for your help! Oleg

4

2 回答 2

1

The problem you're having is due to a typical JS gotcha and not related to Backbone itself. Try

var that = this;
this.model.fetch({ 
    success : function () {
        that.render();
    }
});

The way you're currently passing onDataHandler is problematic as it will cause this to refer to the global object instead of the DialogView, when the function is called.

This fiddle demonstrates the problematic version vs one that works.

(You may also want to take a look at JS strict mode which can shield you from this type of errors.)

于 2013-07-09T13:11:31.610 回答
0

更好的是监听一个事件:

this.model.on("sync", this.render).fetch();

我在寻找其他东西时遇到了这个问题,但目前接受的答案让我抓狂。没有充分的理由在你的代码this中到处撒泼。thatBackbone(下划线)包含一个可以绑定的上下文参数。

that = this没有意义。如果您必须实现过时的 2007 年 Crockford 模式,请说var self = this. 说that = this就是说left = right。大家停下来。

于 2013-08-11T02:31:42.653 回答