1

当我的 Backbone 应用程序的第一页加载时,我会获取一个集合,然后对其进行迭代以呈现页面:

页面路由器:

    home: function ()
    {
        new BodyView ({page:'home'});

        new HomeView();
        new PostView();

        postCollection = new PostCol({userId:getId(),start:0,offset:50});
        postCollection.fetch();
        postView = new Post({collection:postCollection});

    },

帖子视图:

    el:'.stream',
    initialize: function ()
    {
        this.collection.on('reset',this.render.bind(this));
        this.collection.on ('change',this.render.bind (this));
    },
    render: function ()
    {
        this.collection.each (function (model)
        {
            actor = new Actor ({model:model});
            this.$el.append (actor.render().el);
        },this);
        return this;
    },

我现在想要完成的是,当用户在另一个视图中保存一些数据时,它会更新 Post 视图。这就是我所做的,但它不起作用。

其他观点:

     post = new PostModel ({userid:getId(),post:postText,objectid:0});
            post.save({},
            {
                success: function (response)
                {
                    postCol = new PostCol ({userId:getId(),start:0,offset:50});
                    postView = new Post ({collection:postCol});
                    postCol.fetch ().success({change:true});
                },
                error: function (response)
                {
                    console.log (response);
                }
            }
            );
4

1 回答 1

1

看起来您postCollection是全球性的,因此您可以更新现有模型而不是创建新模型。

// find existing model in the collection.
var post = postCollection.get(getId());
// save model with updated info.
    post.save({post:postText},
    {
        success: function (response)
        {
            // if the save succeeded, the Post view will re-render,
            // since you are listening for the 'change' event.
            // so here, you don't really need to do anything.
        },
        error: function (response)
        {
            console.log (response);
        }

    );

除了this.collection.on ('change',this.render.bind (this));在 Post 视图中,您可以在单个 Actor 视图中执行此操作,因此整个集合不会重新渲染。

this.model.on ('change',this.render, this); // 'this' as third parameter replaces the `bind`
于 2013-04-11T04:24:30.657 回答