简体   繁体   中英

Passing data into the render Backbone.js

is it possible to pass the questions variable into the view render?

Ive attempted calling this.render inside the success on the fetch however I got an error, presumably it's because this. is not at the correct scope.

app.AppView = Backbone.View.extend({
    initialize: function(){


        var inputs = new app.Form();

        inputs.fetch({

            success: function() {

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

                app.validate = new Validate(questions);
                app.validate.questions();



            }, // End Success()

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

        }); // End Input.fetch()

        this.render();

    }, // End Initialize

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

    } 

The success callback is called with a different this object than your View instance. The easiest way to fix it is to add something like this before you call inputs.fetch :

var self = this;

And then inside the success callback:

self.render();

I'm not quite sure what you're trying to achieve, but if your problem is calling render from the success callback, you have two options, Function#bind or assigning a self variable.

For more information about "self" variable, see var self = this? . An example:

var self = this;

inputs.fetch({
    success: function () {
        self.render();
    },
    ...
});

You should probably do some reading on JavaScript scopes, for example "Effective Javascript" or search the topic ( for example this MDN article ) online to get a better idea what happens there.

For Function#bind(), see the MDN article about it . With Backbone I suggest you use Underscore/LoDash's _.bind instead though, to make sure it works even where Function#bind() is not supported.

As for more high-level concepts, the fetching operation looks like it belongs to the model or router level and instead you should assign the questions variable as the model of your view. Ideally views don't do data processing / fetching, they're just given a model that has the methods necessary to perform any data transformations you might need.

The views shouldn't even need to worry about where the model comes from, this is normally handled by a router in case of single page applications or some initialization code on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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