Render a View of Backbone Model returns undefined

2019-08-31 06:55发布

问题:

Lets say i have a JSON like this:

JSON example, my json is validated on jsonlint and it works.

json_object = {
"texts_model": {
"hello": "hola",
"icon_text": "Icon!"
},
"collection_vias": {
"text": "hola",
"icon_text": "Icon!"
}
};

I have made a Collection that parse the contents of the json and generates model and collections from this json.

App.TemplatesCollection = Backbone.Model.extend({

    model: App.TemplateModel,
    url: TEMPLATES_SERVICE,

    initialize: function(){
        this.fetch({
            success: (function () {
                console.log(' Success ');
            }),
            error:(function (e) {
                //console.log(' Error: ' + e);
            }),
            complete:(function (e) {
                console.log(' Fetch completado con exito. ');

            })
        });
    },

    //Here i generate all my models and collections.
    parse: function(response){

        App.texts = new App.TemplateModel(response.text_model);
        App.vias = new App.ViasCollection(response.collection_vias);
        return response;
    },

    //I was trying with the get function but i the only thing i got was undefined.
    plain_texts: function(){
        return( this.get('plain_texts') ) ;
    }

});

And the view is like this:

App.TemplateView = Backbone.View.extend({ el: App.$main_content, initialize: function(){ _.bindAll(this, 'render'); }, //Here i pass the template(html source) i want to render. render: function(template){ var html = render(template, this.model.toJSON() ); App.$main_content.html(html); return this; } });

And my start.js where they live all the declarations of my models and views:

//app App = {

init: function(){
    console.log('Iniciando...');

    //variables y constantes
    App.$main_content       = $('#main-content-content');
    App.$main_header        = $('#main-header-content')
    App.$main_navigation    = $('#main-navigation-content');

    //data
    App.templates = new App.TemplatesCollection();

    //views
    App.templateView = new App.TemplateView({model: App.texts});

    //router
    App.router = new App.Router();


},

start: function(){
    //init
    App.init();

    //router
    Backbone.history.start();

}

}

And the router:

//router App.Router = Backbone.Router.extend({

routes:{
    "" : "index",
    ":web" : "url"

},

index: function(){
    console.log("index");

    //Here i do not know what to do, i mean do i have to instiate the View each time i go to index? or only render?
    App.templateView = new App.TemplateView({model: App.texts});
    App.templateView.render("sections/login/form");
},

url: function(web){
    console.log(web);
}

});

//on document ready
$(function(){

    App.start();


});

My problem is that when the html is loaded the only thing i have is: "Uncaught TypeError: Cannot call method 'toJSON' of undefined "

But when i put this on the developer console:

App.templateView = new App.TemplateView({model: App.texts});
App.templateView.render("sections/login/form");

My view is rendered correctly.

Why my view isn't rendered on the load and only when i put my code on the developer console?

How can i render my model on the view on the router url? Why do i have undefined on the html loaded on the developer console?

----EDIT---

All right,

I think i understand. Maybe I'm generating a problem of a thing that does not have to have a problem.

Now my Model is like this:

App.TemplatesCollection = Backbone.Model.extend({

    model: App.TemplateModel,
    url: TEMPLATES_SERVICE,

    plain_texts: function(){
        return this.get('texts')  ;
    },
    initialize: function(){
        this.fetch();
    }

});

And the View:

App.TemplateView = Backbone.View.extend({
    el: App.$main_content,
    initialize: function(){

        console.log(this.collection);
        var ea = this.collection.get('texts');
        console.log(ea);
    },
    render: function(template){
        console.log(this.collection);
        return this;
    }
});

Now i see my collection inside my View.

But when i try to do this to get only the text version on my View:

    var ea = this.collection.get('texts');
    console.log(ea);

Im getting the error of undefined:

Uncaught TypeError: Cannot call method 'get' of undefined

Any idea about how can i resolve this?

I'm trying to solve this by myself. I do not want to look like im asking to develop my solution.

Thanks in advance.

回答1:

It's a little hard to read, but at a quick glance: your App.texts = is in in the parse() function of your Collection. As a result, it gets called once the .fetch() on the collection is performed... until then, your App.texts is undefined!

If App.texts is undefined when you create the TemplateView, then the view's model will actually be undefined, and so, in the render, when the template engine you use is doing a toJSON(), it will say that it has an undefined value...

There may be other problems, but this one is the most glaring. Here is a quick&dirty fix: once the fetch() is done, your collection will trigger a reset event. That's your cue for doing the rendering. So, what you can do, is instead of passing the model to the View, you can pass the collection instead:

 App.templateView = new App.TemplateView({collection: App.templates});

Now, in your View's initialize, you can do something like:

 if(App.texts) {
   //Your collection has already fetched and already went through parse()
   this.model = App.texts;
   this.render("sections/login/form");
 } else {
   //Your collection hasn't done the fetch yet
   view = this;
   this.collection.one("reset", function(){
     view.model = App.texts;
     view.render("sections/login/form");
   });
 }

If you give a collection as a param to a View's construction, it'll be stored in this.collection, same as with model. The idea here is to use the events to know when to do the rendering, and also let the view tell you when it's ready to render. You could also do something in your render() function to check if the model is defined!

To see if this analysis is correct, you can put a console.log(App.texts); in your index function in the router.

One way to make the code a bit more obvious is to initialize your App.texts and App.vias directly in your App's init. And give a reference to them to your AppTemplatesCollection if you really need to side-load them in the parse of AppTemplates' fetch(). The difference that makes is that you can bind to events from the App.vias collection ('add', 'remove', 'reset') or to the App.texts model ('change').

Another thing I noticed is that you have a collection of App.TemplateModel but you are still creating a App.texts where you put the result of the fetch into your own instance of App.TemplateModel? That doesn't seem right, maybe you have a reason for doing so, but in the most general case, the collection is suppose to handle the creation of the models, especially after a fetch!

The usual use case of the parse() method is to side-load data (other models/collection), change the format (from XML to something JS can understand) or to remove useless keys (for instance user: {id: ..., name: ... }, you'll return response.user so that Backbone can play with the correct hash directly). What you are doing here seems to fall out of this pattern so maybe it's a cause for worry?



回答2:

In your code you have created collection as :

App.TemplatesCollection = Backbone.Model.extend({
//rest of the code

If you want to create a collection you need to extend Backbone.Collectionand not Backbone.Model.

App.TemplatesCollection = Backbone.Collection.extend({
//rest of the code