backbone.js view renders before model fetch

前端 未结 5 983
自闭症患者
自闭症患者 2021-01-05 15:51

I\'m trying to make a small backbone.js app, but struggle with the order of things.

In my html file, I have two script blocks in the header:



        
5条回答
  •  不思量自难忘°
    2021-01-05 16:23

    Clearly from the previous answers, you know that you need to render on the fetch success callback, however I think you problem is a bit more than that. Namely, your home route is used to build myModelView immediately rather than when its data loads. This is happening because you are calling render() in order to append to body. Instead, try and initialize the view with an existing element. This way you can delay the call for render until fetch has completed:

    window.MyApp = Backbone.Router.extend({
        routes: {
            '': 'home'
        },
    
        initialize: function () {
    
        },
    
        home: function() {
            var $body = $(document.body).empty();
            var myModelEl = $("
    ").appendTo($body); this.myModelView = new MyModelView({ model: window.mymodel, el: myModelEl }); } });

    Now, you haven't called render() yet, but your view is successfully attached to the DOM as you intended.

提交回复
热议问题