主干:渲染前获取

Backbone: Fetch before rendering

本文关键字:获取 主干      更新时间:2023-09-26

我想添加一个新项目到我的主干集合使用:

window.bearList.create({ name: "Tina" } );

这将正确地将新项目保存到服务器,因为之后我可以在服务器上看到它,这就是我想要的。(我正在使用MongoDB)

{"name":"Tina","_id":"53b41d92b7083d0b00000009","__v":0}

我在我的bearList ListView中有这个绑定:

    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.bind('add', this.render);
    },

问题是,上面的代码只是将以下内容添加到我的集合视图中,直到我重新加载页面。

 {"name":"Tina"}

我已经尝试使用model.save()回调,但我仍然有同样的问题。

就像我说的,服务器上的一切看起来都很好,一旦我重新加载页面,集合就会有更正版本的"Tina"。

但是由于某种原因,它没有得到ListView的'render'事件的完整模型。我试过在ListView渲染方法上单独抓取每个模型,但这不起作用,无论如何都是不好的做法。

有人能帮我一下吗?

这是我的完整代码:

window.ListView = Backbone.View.extend({
    tagName: 'ul',
    className: 'list-group',
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.bind('add', this.render);
    },
    render: function(){
        this.$el.html(" ");
        this.collection.each(function(item){
        var listItemView = new ListItemView({ model: item });
        this.$el.append(listItemView.render().el);
        }, this);
    return this;
    },
});

window.ListItemView = Backbone.View.extend({
    tagName: 'li',
    className: 'list-group-item',
    initialize:function () {
        this.model.bind("change", this.render);
    },
    render:function () {
        console.log(JSON.stringify(this.model.toJSON()));
        this.$el.html("<a href='#"+ this.model.hashType + "/"+this.model.get('_id')+"' >" + this.model.get('name') + "</a>");
    return this;
    }
});

Just pass wait:true.

window.bearList.create({ name: "Tina" }, {wait: true} );

http://backbonejs.org/Collection-create

传递{wait: true}如果您想在添加之前等待服务器新模型的集合。

监听sync事件,因为add只会添加您在主干中创建的值。http://backbonejs.org/同步

还有一个提示:使用listenTo来使用Backbone的更多特性。而不是

initialize:function () {
    this.model.bind("change", this.render);
},

使用:

initialize:function () {
    this.listenTo( this.model, "change", this.render );
},