3

使用 Backbone 从 JSON 服务收集集合,我使用视图初始化来激活提取,但是我现在想将 JSON 数组传递回视图,但我不确定如何实现这一点......

以下代码是我目前正在使用的:

app.AppView = Backbone.View.extend({

        initialize: function(){


            // Instanciate a new Form collection (which is derrived from the input model)
            var inputs = new app.Form();

            // Perform a GET on the model url to the service
            inputs.fetch({

                success: function() {

                    var questions = inputs.get(0).toJSON().Questions;

                    console.log(questions);



                }, // End Success()

                error: function(err){
                    console.log("Couldn't GET the service " + err);
                }

            }); // End Input.fetch()

            this.render();

        }, // End Initialize

        render: function(){
            el: $('#factfinder')
            var template = _.template( $("#form_template").html(), {} );
            this.$el.html(template);

        } 

    }); // End AppView.Backbone.View.extend()
4

2 回答 2

1

首先fetch是异步的。因此,当请求从服务器返回时,您需要始终调用渲染。最好的方法是监听服务器上的resetandsync事件并调用 render 方法。

app.AppView = Backbone.View.extend({
        el: $('#factfinder'),
        initialize: function() {

            var inputs = new app.Form();

            // Listen top the events that calls the success method
            this.listenTo(inputs, 'sync reset', this.renderView);
            //  to bind the this context
            _.bindAll(this, 'renderView');
            // Perform a GET on the model url to the service
            inputs.fetch({
                error: function(err){
                    console.log("Couldn't GET the service " + err);
                }
            }); // End Input.fetch()

        }, // End Initialize
        renderView: function() {
           var questions = inputs.get(0).toJSON().Questions;
           console.log(questions);
           // Call render when the request comes back with response
           this.render();
        },
        render: function(){
            var template = _.template( $("#form_template").html(), {} );
            this.$el.html(template);
        } 

    }); // End AppView.Backbone.View.extend()

而且您在渲染方法中有语法错误

el: $('#factfinder')

应该是

var el = $('#factfinder')

或者你可以把它移到渲染之外

于 2013-07-26T23:28:27.173 回答
0

您通常不会将 JSON 传递给render,而是将model. 此外,您需要render在回调内部success调用,因为获取是异步的:

// store a reference to the view object
var self = this;

inputs.fetch({
    success: function() {
        var questions = inputs.get(0).toJSON().Questions;
        console.log(questions);
        this.model = new Backbone.Model(questions);
        self.render();
    }, // End Success()
    error: function(err){
        console.log("Couldn't GET the service " + err);
    }
}); // End Input.fetch()

现在render,您可以从模型中获取 JSON:

this.$el.html(template(this.model.toJSON()));

这似乎是一种迂回的做法——从 JSON 构建模型,然后从模型中获取 JSON。但这是设计使然。它允许模型有机会做它的事情,设置它拥有的任何默认值,并验证从服务器返回的原始数据。

于 2013-07-26T21:37:56.070 回答