【问题标题】:low coupling: add a model to a collection of a different view低耦合:将模型添加到不同视图的集合中
【发布时间】:2013-05-19 23:49:26
【问题描述】:

我正在构建一个 Backbone/Marionette 应用程序来列出不同的卡片组。布局左侧有一个 ItemView,其中包括一个用于添加新集合的输入字段和一个用于列出卡片集合的 CompositeView。

Cards.module("Set.SideBar", function(SideBar, App) {
    SideBar.SideBarView = Backbone.Marionette.ItemView.extend({
        template: "#set-sideBar",
        className: "well sidebar-nav",
        ui: {
            saveBtn: "a.saveSet",
            setName: "input[type=text]"
        },
        events: {
            "click .saveSet": "saveSet"
        },
        saveSet: function(ev) {
            ev.preventDefault();

            var newSetName = this.ui.setName.val().trim();
            var newSet = new Cards.Entities.Set({ name: newSetName });

            newSet.save();

            // How to add the model to the collection?
        }
    });
});

我正在寻找将 newSet 添加到下面的 CompositeView 集合中的最佳方法。是否有任何干净的低耦合解决方案来解决这个问题?我对backbone.js 很陌生,无法想象这完全不寻常,但不知何故,我无法在相关文档中找到我的问题的答案——或者只是不理解它们。

Cards.module('Set.List', function(List, App) {
    List.SetItemView = Backbone.Marionette.ItemView.extend({
        tagName: "tr",
        template: "#set-list-item"
    });

List.SetView = Backbone.Marionette.CompositeView.extend({
        tagName: "table",
        className: "table table-bordered table-striped table-hover",
        template: "#set-list",
        itemView: List.SetItemView,
        itemViewContainer: "tbody",
        modelEvents: {
            "change": "modelChanged"
        },

        initialize: function() {
            this.collection.fetch();
        }
    });
});

提前感谢您的帮助!

我现在的情况:

感谢您的两个答案,他们引导我朝着正确的方向前进。 collection.create 提示也非常有用,解决了我面临的另一个问题!

在 Marionette.Controller 中,我做这样的事情并简单地分享集合参考:

var setLayout = new Cards.Set.Layout();
Cards.mainRegion.show(setLayout);

var sets = new Cards.Entities.SetCollection();
var listView = new Cards.Set.List.SetView({ collection: sets });
setLayout.listRegion.show(listView);

var sideBarView = new Cards.Set.SideBar.SideBarView({ collection: sets });
setLayout.sideBarRegion.show(sideBarView);

并且新模型只是通过 collection.create 而不是 .save() 和 .add() 添加的。

【问题讨论】:

  • 为什么不与侧边栏视图共享集合实例并使用 Collection.add 方法添加新模型?

标签: backbone.js marionette backbone-views backbone.js-collections


【解决方案1】:

Backbone.Collection.add 可用于将模型添加到现有的主干集合。 http://backbonejs.org/#Collection-add

另外,查看 Collection.Create - http://backbonejs.org/#Collection-create

如果您的模型被持久化,然后立即添加到集合中,您可以跳过 model.save() 然后 collection.add() 并直接使用 collection.create(model)

编辑:如前所述,让集合实例从侧边栏视图可见

【讨论】:

    【解决方案2】:

    为了保持视图解耦,您可以从一个视图引发事件,其他视图可以随意收听和处理。

    【讨论】:

    • 但是是否也可以发送一些带有事件的自定义数据?
    • 是的,您作为第二个参数传递给 trigger() 的任何内容都将作为任何事件侦听器的第一个参数传递
    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 2013-02-09
    • 2016-04-29
    • 1970-01-01
    • 2014-12-02
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多