保存模型时更新Backbone视图

时间:2012-01-02 06:51:48

标签: javascript backbone.js

我有以下情况 -

window.Wine = Backbone.Model.extend({
  urlRoot: '/wines'

});
window.WineCollection = Backbone.Collection.extend({
   model: Wine,
   url: "/wines"
});

我有一个模型和相应的集合定义。

window.WineListView = Backbone.View.extend({
    el: '#wineList',
    initialize: function () {
        this.model.bind("reset", this.render, this);
        this.model.bind("add", function (wine) {
            alert("model added");
        });
    },
    render: function (eventName) {
        _.each(this.model.models, function (wine) {
            $(this.el).append(new WineListItemView({
                model: wine
            }).render().el);
        }, this);
        return this;
    }
});
window.WineListItemView = Backbone.View.extend({
    tagName: "li",
    initiliaze: function () {
        this.render();
    },
    render: function (eventName) {
        var template = _.template($('#wine-list-item').html());
        $(this.el).html(template(this.model.toJSON()));
        return this;
    }
});

以上视图为每个模型创建单独的列表项。

window.WineView = Backbone.View.extend({
    el: $("#mainArea"),
    initialize: function () {
        this.render();
    },
    render: function (eventName) {
        var template = _.template($("#wine-details").html(), {});
        $(this.el).html(template);
    },
    events: {
        "click #save_form": "save_form"
    },
    save_form: function () {
        var wine = new Wine();
        wine.save();
        return false;
    }
});
window.HeaderView = Backbone.View.extend({
    el: '.header',
    initialize: function () {
        this.render();
    },
    render: function (eventName) {
        var template = _.template($('#header').html());
        $(this.el).html(template());
        return this;
    },
    events: {
        "click .new": "newWine"
    },
    newWine: function (event) {
        var wine_View = new WineView();
        wine_View.render();
    }
});

在WineView中,单击表单的提交按钮时,将保存模型。 Backbone.sync函数被覆盖。

var AppRouter = Backbone.Router.extend({
    routes: {
        "": "list"
    },
    list: function () {
        this.wineList = new WineCollection();
        this.wineListView = new WineListView({
            model: this.wineList
        });
        this.wineList.fetch();
    }
});
var app = new AppRouter();
Backbone.history.start();
var header = new HeaderView();

我担心的是,当保存模型时,WineListView不会刷新并显示已添加的新模型。确切地说,this.mode.bind(" add")没有被调用。

我为这个问题的冗长而道歉。但是,这已经困扰了我近一个星期。任何帮助是极大的赞赏。

干杯!

2 个答案:

答案 0 :(得分:5)

从未调用过add的原因正是如此 保存葡萄酒wine.save();后,您应添加成功功能并将其添加到winelist集合

试试这个:

wine.save(wine.toJSON(), {
    success: function(){ 
        // model was saved successfully, now add it to the collection
        yourwinelist.add(wine);
        // if you can't access your wine list from this context, you might want to raise an event, and pass the wine, to catch it somewhere else:
        obj.trigger('myWineAdded', wine); // this can be raised on a global event aggregator
    },
    error: function(){ 
        // handle app when saving to server fails
        alert('failed to save wine');
    }
});

关于事件聚合器想法的更多信息请检查:
Routing and the event aggregator coordinating views in backbone.js

答案 1 :(得分:1)

从我所看到的,你实际上并没有新模型添加到集合中。一个简单的方法是使用集合的create方法(假设您已经使集合可用):

save_form: function () {
    this.collection.create({ MODEL ATTRIBUTES HERE … });
    return false;
}

正如文件所述

  

[t]创建方法可以接受属性哈希或现有的未保存模型对象。

像这样创建新模型,如果我没弄错的话,应该在集合上触发add事件

另一种方式,根据文档应该肯定会触发add事件(再次,在集合上,而不是模型!)

save_form: function () {
    var wine = new Wine();
    this.collection.add(wine);
    return false;
}
  

将一个模型(或一组模型)添加到集合中。点燃“添加”   事件,您可以通过{silent:true}来压制。

无论如何,请记住更改事件绑定:

this.collection.bind("add", function (wine) {
    alert("model added");
});