【问题标题】:Responding to category model change in Backbone relational响应 Backbone 关系中的类别模型变化
【发布时间】:2012-06-09 14:15:42
【问题描述】:

我使用 Backbone Relational 设置了模型关系,其中 Item 属于 Column。 向列中添加项效果很好,但是我如何引用项的现有视图,以便将其从旧列中删除?(因此,项目前是跨列复制。)

请查看此 JSFiddle - http://jsfiddle.net/geVPp/1(我认为代码需要在 ColumnView removeItem 事件处理程序中实现,但我可能错了)。

(示例实例位于脚本底部,因为我还没有 UI 控件。)

这是小提琴中的 ColumnView:

var ColumnView = Backbone.View.extend({
className: 'column',
tagName: 'div',
template: Handlebars.compile($('#column-template').html()),
initialize: function() {
  _.bindAll(this, 'render', 'renderItem', 'removeItem');
  this.model.bind('change', this.render);
  this.model.bind('reset', this.render);
  this.model.bind('add:items', this.renderItem);
  this.model.bind('remove:items', this.removeItem);
},
render: function() {
  return $(this.el).html(this.template(this.model.toJSON()));
},
renderItem: function(item) {
  var itemView = new ItemView({model: item});
  this.$('.items').append($(itemView.render()));
},
removeItem: function(item) {
  // @todo -- How do I reference the item model's view, in order to remove the DOM element?
}
});

【问题讨论】:

    标签: javascript backbone.js backbone-relational


    【解决方案1】:

    不幸的是,Backbone 没有内置方式;您必须手动跟踪您的子视图(以及它们映射到的模型)。

    Backbone.Marionette 有一个 CollectionView 类可以为您自动执行此操作。或者你可以自己滚动类似于UpdatingCollectionView。

    如果您想要快速修复,您可以保留对视图的引用作为模型对象的变量,但这很糟糕,因为它会阻止您显示同一模型的多个视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多