javascript - 当集合更改时更新主干 View

标签 javascript backbone.js requirejs

当我的 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;
    },

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

其他 View :

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

最佳答案

看起来您的 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);
        }

    );

您可以在单个 Actor View 中执行此操作,而不是在 Post View 中使用 this.collection.on ('change',this.render.bind (this));集合不会重新渲染。

this.model.on ('change',this.render, this); // 'this' as third parameter replaces the `bind`

关于javascript - 当集合更改时更新主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939572/

相关文章:

javascript - 具有混合日期格式的 jquery tablesorter 插件无法在 IE/Safari 中工作,但可以在 FF、O、C 中工作

javascript - 带参数的 Backbone.blazer 路由

javascript - 如何在 RequireJS 中模拟单元测试的依赖项?

javascript:使后端数据库更改立即反射(reflect)到浏览器,这可能吗?

javascript - 正则表达式删除除数字之外的所有特殊字符?

javascript - 在 highChart 中自定义堆积柱形图

javascript - Requirejs,杏仁, Backbone , Handlebars

javascript - Backbone.js 按钮单击事件会针对按钮的所有实例触发,而不仅仅是被单击的实例。为什么?

javascript - RequireJS 中的命名模块与未命名模块

javascript - 间歇性 "Bootstrap's JavaScript requires jQuery”错误