1

我是backbone.js 的新手,我的应用程序有一些问题。我有一个依赖于 json 数据源的集合。我能够在我的 parse 方法中 console.log json。这足以将集合绑定到我的视图吗?我不明白 fetch 方法的使用。

我的收藏如下所示,

(function (collections,model) {
collections.Directory = Backbone.Collection.extend({
        initialize : function(){
            console.log('we are here');
            },
        model:model.item,
        url:'collections/json/data.json',
        parse:function(response){
                console.log(response);
                return response;
            }
    });
})(app.collections,app.models);

我的主视图看起来像这样,

(function(views,collections){

views.masterView = Backbone.View.extend({
         el : $("#contacts"),
        initialize : function(){
            console.log('view initialize inside render');
            this.render();
            this.$el.find("#filter").append(this.createSelect());
            this.on("change:filterType", this.filterByType, this);
            this.collection.on("reset", this.render, this);
            this.collection.on("add", this.renderContact, this);
            //console.log('we are here'+app.collections.CollectionItems.fetch());
            console.log('view initialize');
        },

        render : function(){

            this.$el.find("article").remove();
            _.each(this.collection.models,function(item){

                this.renderContact(item);
               },this);

            },
             renderContact: function (item) {
            views.contactView = new app.views.ContactView({
                model: item
            });
            this.$el.append(contactView.render().el);
        },
            getTypes : function () {
            return _.uniq(this.collection.pluck("Qno"));
        },
    createSelect : function () {

        var select = $("<select/>", {
                    html: "<option value='all'>All</option>"
                });
    _.each(this.getTypes(), function (item) {
        var option = $("<option/>", {
            value: item.toLowerCase(),
            text: item.toLowerCase()
        }).appendTo(select);
    });
    return select;
    },
     events: {
            "change #filter select": "setFilter",
            "click #add": "addContact",
            "click #showForm": "showForm"
        },
    setFilter : function(e){
        this.filterType = e.currentTarget.value;
        this.trigger("change:filterType");

    },
    filterByType: function () {
    if (this.filterType === "all") {
        this.collection.reset(contacts);
        routerURL.navigate("filter/all");
    } else {
        this.collection.reset(contacts, { silent: true });
        var filterType = this.filterType,
            filtered = _.filter(this.collection.models, function (item) {
            return item.get("type").toLowerCase() === filterType;
        });
        this.collection.reset(filtered);
        routerURL.navigate("filter/"+filterType);
    }
},
    addContact : function(e){
        e.preventDefault();
        var contModel = {};
        $("#addContact").children("input").each(function(i, el){
            if($(el).val() !== "")
                contModel[el.id] = $(el).val();

        });
        contacts.push(contModel);
        if (_.indexOf(this.getTypes(), contModel.type) === -1) {
                this.collection.add(new Contact(contModel));
                this.$el.find("#filter").find("select").remove().end().append(this.createSelect());
            } else {
                this.collection.add(new Contact(contModel));
            }
    },
    showForm : function(){
        this.$el.find("#addContact").slideToggle();   
    }

        });
      })(app.views,app.collections);

我的模型很简单,看起来像这样,

(function ( models ) {
    models.Item = Backbone.Model.extend({
        defaults :{Qno:'1',Desc:'hello'}
        });
})( app.models );

我有一个 js 文件实例化视图和集合

    (function () {

        window.app = {};
        app.collections = {};
        app.models = {};
        app.views = {};
        app.mixins = {};

       $(function(){
                app.collections.CollectionItems = new app.collections.Directory();
                //app.collections.CollectionItems.fetch();
                //console.log(app.collections.CollectionItems.fetch());

                app.collections.CollectionItems.fetch({
                    success: function (collection,response) {
                        console.log(response);
                    }
                });
                //console.log(app.collections.CollectionItems.toJSON());
                console.log('coll started');
                app.views.app = new app.views.masterView({collection: app.collections.CollectionItems});
                console.log('view is jus about fine!!');
                //app.views.pagination = new app.views.PaginatedView({collection:app.collections.paginatedItems});
        });






    var ContactsRouter = Backbone.Router.extend({
    routes: {
        "filter/:type": "urlFilter"
    },
    urlFilter: function (type) {
        master.filterType = type;
        master.trigger("change:filterType");
    }
});

    var routerURL = new ContactsRouter();

    Backbone.history.start();
})();

我的登陆页面看起来像这样,里面有一个模板

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Backbone.js Web App</title>
        <link rel="stylesheet" href="css/screen.css" />
    </head>
    <body>

        <div id="contacts">

</div>

        <script id="contactTemplate" type="text/template">

            <h1><%= Qno %></h1>

        </script>
        <script src="js/jquery.js"></script>
        <script src="js/underscore-min.js"></script>
        <script src="js/backbone-min.js"></script>
        <script src="app.js"></script>
        <script src="collections/Directory.js"></script>
        <script src="models/item.js"></script>
        <script src="views/masterView.js"></script>
         <script src="views/simpleView.js"></script>
        <!--<script src="js/backbone.paginator.js"></script>-->
    </body>
</html>

我只是无法理解这一点。视图不使用集合数据呈现。请帮忙!

4

1 回答 1

1

我认为这是因为您的集合上的 fetch 方法是异步执行的,因此在您创建视图时尚未完成(如果您查看控制台,我希望成功回调中的日志语句显示在下面的日志语句之后)。这意味着在填充集合之前调用您的视图渲染方法,并且永远不会触发重置事件(您在视图中绑定到该事件)。

尝试更新实例化所有内容的代码,如下所示:

   $(function(){
            app.collections.CollectionItems = new app.collections.Directory();
            //app.collections.CollectionItems.fetch();
            //console.log(app.collections.CollectionItems.fetch());

            app.collections.CollectionItems.fetch({
                success: function (collection,response) {
                    console.log(response);
                    app.views.app = new app.views.masterView({collection: app.collections.CollectionItems});
                }
            });
    });
于 2013-01-13T01:50:47.770 回答