繁体   English   中英

从集合中获取json以在骨干.js中查看

[英]Getting a json from collection to view in backbone.js

我刚好接触过ribs.js,我的应用遇到了一些问题。 我有一个依赖于json数据源的集合。 我可以在我的解析方法中console.log json。 这足以将集合绑定到我的视图吗? 我不明白提取方法的使用。

我的收藏如下所示

(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>

我只是无法解决这个问题。 该视图未使用收集数据呈现。 请帮忙!

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

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

   $(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});
                }
            });
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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