Backbone Marionette Displaying before fetch comple

2019-02-15 04:27发布

问题:

I know i am doing something stupid but my backbone marionette app is giving me template errors that don't make sense. It appears to be rendering a single item before the fetch event happens.

_.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g
};


MyApp = new Backbone.Marionette.Application();
MyApp.addRegions({
    TagsRegion: "#tagsHolder"
});



MyApp.NoItemsView = Backbone.Marionette.ItemView.extend({
    template: "#show-no-items-message-template"
});


MyApp.Tag = Backbone.Model.extend({

});
MyApp.TagCollection = Backbone.Collection.extend({
    model: MyApp.Tag,
    url: '/API/Tag'
});
MyApp.TagItemView = Backbone.Marionette.ItemView.extend({
    template: "#tag-template",
    tagName: 'li'
});


MyApp.TagCollectionView = Backbone.Marionette.CollectionView.extend({
    itemView: MyApp.TagItemView,
    emptyView: MyApp.NoItemsView,
    tagName: 'ul'
});


MyApp.addInitializer(function(options){
    var tagCollection = new MyApp.TagCollection({
    });
    var tagCollectionView = new MyApp.TagCollectionView({
        collection: tagCollection
    });

    tagCollection.fetch();
    MyApp.TagsRegion.show(tagCollectionView);
});

and my html page is

<div id="TagsDiv">
    <h1>Tags</h1>
    <div id="tagsHolder"></div>
</div>    
<script type="text/template" id="show-no-items-message-template">
    No items found.
</script>

<script type="text/template" id="tag-template">
    {{ TagName }}
</script>


    <script type="text/javascript" src="/Scripts/Views/Home/Upload.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            MyApp.start();
        });

If I remove the mustaches from my tag-template it displays 1: " TagName " then when the fetch completes it shows the right number.

if i put the mustaches back in i get "TagName is not defined"

I feel that i have one of my patterns backwards. I am just too close to see it.

Thanks -Mark

回答1:

The problem is this line in your initializer

var tagCollection = new MyApp.TagCollection({
    });

When you pass an empty object literal in to a Backbone.Collection constructor, Backbone creates an empty model in the collection. To fix this, just remove the object literal:

var tagCollection = new MyApp.TagCollection()

and it won't have the empty item in it anymore.



回答2:

Try:

tagCollection.fetch({ wait: true });


回答3:

Modified the Model to have a default value of anything i want to template. Feels Klugy but it gives me an app that works.

MyApp.Tag = Backbone.Model.extend({
    defaults :
        {
            TagName : 'None'
        }
});