Backbone ViewModel 与(数据)模型

Backbone ViewModel vs (Data) Model

在 backbone 中,我可以以不同的方式使用我的模型。

据我了解,(数据)模型用于存储数据(可能由 RESTful 网络服务器提供),ViewModel 用于存储有关特定视图的信息(视图 hidden/shown 例如状态)。

我的大部分知识来自 this SO 问题。

阅读 this 文章后,作者说:

Render UI Upon Data Change, Not User Interaction

The flow is : User interaction -> data change -> view render.

For instance, if we are writing a play/pause toggle button in an audio player, the flow would be:

  • The user hits ‘play’
  • The model (data) state changes to ‘playing’
  • The view renders in ‘playing’ mode

Following this pattern ensures that changes to the state triggered from other sources (such as fast forward, new playlist, network error, etc.) will toggle our button to do the right thing. In other words, we have a single source of truth: whenever our model changes we know we should render our button.

var PlayPauseButton = Backbone.View.extend({
  tagName: 'li',
  className: 'icon',
  initialize: function(){
    this.model.on('change:status', this.render, this);
  },
  render: function(){
    this.$el.removeClass('icon-play').removeClass('icon-pause');
    this.$el.addClass('icon-' + (this.isPlaying() ? 'pause' : 'play'));
  },
  events: {
    'click': function(){
      this.model.set('status', this.isPlaying() ? 'paused' : 'playing');
    }
  },
  isPlaying: function(){
    return this.model.get('status') === 'playing';
  }
});

我开始想知道使用每一个的优点和缺点。

假设我们每个视图只有一个模型(我知道我们可以有更多,但如果我们限制为一个)。 我能想到,

ViewModel 专家:

缺点:

(数据)模型优点:

缺点:

我这样想对吗?

我应该为我的数据和视图建立模型吗?

这对集合有何作用?

我知道Backbone很宽松,没有硬性规定。 但是,有没有人有使用其中一种的真实经验?或者两者都有?

感谢任何帮助。

您实际上假设您不能在后端使用您的 Data(Domain) 模型,并且您需要将数据作为 ViewModel 对象来处理。 Stack Overflow 领域经验丰富的专业人士教我的方法是:

1.) 始终将 ViewModel 用于视图。不要使用域模型。域模型通常不完全适合视图,这导致人们使用魔术字符串、请求缓存甚至会话来存储特定于视图的信息,所有这些都是不必要的。

2.) 由于这限制了您所指出的方式,例如无法使用 Backbone 中内置的数据模型方法,请使用您自己创建的对象映射器或之前别人做的一个,在需要用到的时候把ViewModel的属性映射到Data模型的属性上。

这使您可以拥有高度特定的 ViewModel,而无需担心无法使用 Backbone 自己的数据模型。

关于你关于集合的稍微独立的问题,你应该存储 ViewModel 对象的集合以用于你需要的其他东西。例如,如果您有一个汽车列表,您应该为您的 CarListViewModel 提供一个 CarViewModel 对象列表。当您在模型的阶梯上走这么远时,您是否应该选择使用数据对象,它的影响较小,但仍应避免。