1

我将从我对这两个框架的新手开始,但我对迄今为止从它们中学到的东西感到非常兴奋。我做事的方式有了很大的改进。

我想在一张桌子上显示一组项目(旅行路线)。我只想在表格中显示几个行程字段,因为字段很多。当您编辑/添加项目时,我想显示一个表单来编辑不同区域或模式中的所有字段,显然当您保存列表/表格时会更新。我不确定构建此结构的最佳方法,并希望有人可以为我指出正确的方向,或者甚至更好地举一个类似的例子。到目前为止,我的搜索不足。看来我应该对列表使用复合视图,但是如何最好地将选定的项目传递出去以进行编辑是我有点卡住的地方。任何指针将不胜感激。

4

1 回答 1

7

我会为表格使用 CompositeView,为表单使用 ItemView。显然这是不完整的,但它应该让你开始。其实……我有点得意忘形了。

以下是基本结构和流程的一些想法。实现细节,包括模板,我会留给你。

表/行视图:

// each row in the table
var RowView = Backbone.Marionette.ItemView.extend({
  tagName: "tr"
});

// This could be a table tag itself, or a container which holds the table.
// You want to use a CompositeView rather than a CollectionView so you can
// render the containing template (the table tag, headers), and also, it works
// if you have an actual collection model (ItineraryList, etc).
var TableView = Backbone.Marionette.CompositeView.extend({
  itemView: RowView,
  collectionEvents: {
    "change": "render"
  }
});

表单视图:

// This would be a simple form wrapper that pulls default values from
// its model.  There are some plugins in this space to help with
// forms in backbone (e.g. backbone-forms), but they may or may not
// be worth the bloat, or might be tricky to work with Marionette.
var FormView = Backbone.Marionette.ItemView.extend({
  events: {
    "submit form": "onFormSubmit"
  },

  data: function () {
    // here you'd need to extract your form data, using `serializeArray`
    // or some such, or look into a form plugin.
    return {};
  },

  // Clearly this is incomplete.  You'd need to handle errors, 
  // perhaps validation, etc.  You probably also want to bind to 
  // collection:change or something to close the formview on success.
  //
  // Re-rendering the table should be handled by the collection change 
  // event handler on the table view
  onFormSubmit: function (e) {
    e.preventDefault();

    if (this.model.isNew()) {
      this.collection.create(this.data());
    } else {
      this.model.save(this.data());
    }
  }
});

在加载过程中的某个地方,您将实例化一个集合并显示它:

// first off, somewhere on page load you'd instantiate and probably fetch
// a collection, and kick off the tableview
var itineraries = new Itineraries();
itineraries.fetch();

// For simplicity I'm assuming your app has two regions, form and table, 
// you'll probably want to change this.
app.table.show(new TableView({collection: itineraries}));

为编辑和新行程链接制作路线是有意义的,但如果您的表单处于模式中,您可能希望绑定到按钮点击。无论哪种方式,您都会打开这样的表单:

// in the router (/itineraries/edit/:id) or a click handler...
function editItinerary(id) {
  var itinerary = itineraries.get(id);
  // then show a view, however you do that.  If you're using a typical 
  // marionette region pattern it might look like
  app.form.show(new FormView({
    collection: itineraries, 
    model: itinerary
  });
}

// once again, a route (/itineraries/new), or a click handler...
function newItinerary() {
  app.form.show(new FormView({
    collection: itineraries, 
    model: new Itinerary()
  }));
}
于 2013-05-02T21:28:19.227 回答