0

我有两个函数循环遍历 Backbone 集合中的所有模型,并保存已更改的模型,或销毁已选择删除的模型。我需要做的是整理成功和错误,以便我可以通知“X 个更改/删除成功”和/或“更改/保存 X 个域时出错”。

我没有保存/销毁 Backbone 集合的经验,只有模型;并且在互联网上找不到任何显示如何执行此操作的内容。

保存和删除由父视图中的事件调用。

相关代码:

App.Views.SiteDomains = Backbone.View.extend({
    el: '.site-domains',
    initialize: function() {
        this.collection.on('all',this.render, this);
    },
    render: function() {
        $('.site-domains').empty();

    this.collection.each( function(model)
    {
        var view = new App.Views.SiteDomain({model: model});
        this.$('.site-domains').append(view.render().el);

        return this;
    });
},
saveDomainChanges: function() {

    this.collection.each( function(model)
    {
        var ref = model.get('ref');

        if ($('#' + ref).val() != model.get('domain')) {

            $('.save-domains').prop('disabled', true);

            var fields = $(this.el).find('form').serializeArray(), data = {};

            $.each(fields, function(i, pair)
            {
                data[pair.name] = pair.value;
            });

            model.save(data, {

                wait:true,
                success: function(model, response, event)
                {
                    // Pass each success to notification function
                },

                error: function(model, response, event)
                {
                    // Pass each error to notification function
                }
            });
        }
    });
    $('.save-domains').prop('disabled', false);
},
removeDomain: function() {
    this.collection.each( function(model)
    {
        var ref = model.get('ref');

        if ($('#remove-' + ref).prop('checked'))
        {
            model.destroy({
                wait:true,
                success:function() {
                    // Pass each success to notification function
                },
                error: function() {
                    // Pass each error to notification function
                }
            });
        }
    });
}
});

非常非常多,非常感谢任何可以提供帮助的人!:)

4

1 回答 1

2

您可以根据您的应用程序设计使用事件聚合器并创建模型/视图或仅用于通知的 POJO。像这样的东西:

// Event aggregator
App.vent = _.extend({}, Backbone.Events);

// POJO for the notifications
App.notifications = {
    var onCreateSuccess = function (model, response) {
        ...
    };
    var onCreateError = function (model, response) {
        ...
    };
    App.vent.on('sitedomain:create:success', onCreateSuccess);
    App.vent.on('sitedomain:create:error', onCreateError);
};

// Add event triggering to corresponding callbacks
model.save(data, {
    wait:true,
    success: function(model, response, event) {
        App.vent.trigger('createdomain:create:success', model, response);
    },

    error: function(model, response, event) {
        App.vent.trigger('createdomain:create:error', model, response);
    }
});
于 2012-05-31T11:47:43.737 回答