将 if/then 逻辑移动到视图或模型中还是保留在模板中?

Move if/then logic into view or model or keep in template?

在使用 backbone 为一家引擎设计公司创建 Web 应用程序后,我想知道是否应该将 "if/then" 逻辑移出 html 模板。

为了帮助阐明我的意思,这里有两个我目前在生产中使用的示例。

如果我将 if/then 逻辑移出模板,我会把它移到视图中,但我不确定那是 "right" 方式还是 "backbone" 方式做事。

是我做出了错误的设计决策,还是我所做的一切正常?

谢谢!

简单示例 1:

在视图中:

//m is the model used by the view
return Backbone.View.extend({
    template: _.template(tmpl, null, { variable: 'm' }),

在模板中:

 {% if(m.title) { %}
      <h4> {%- m.title %} </h4>
 {% } else { %}
      <h4>Experiment Title Goes Here</h4>
 {% } %}

复杂示例 2:

在视图中:

//args are the model attributes passed into the view
initialize: function (args) {
    this.currentEngine = args.currentEngine;
    this.engineDisplay = args.engineDisplay;
    this.engineType = args.engineType;
    this.isCurrent = this.model.isCurrent(this.currentEngine);

},

render: function () {

    this.$el.html(this.template({
    engineDisplay: this.engineDisplay,
    engineType: this.engineType,
    isCurrent: this.isCurrent;

}));

在模板中:

 {% if(!engineDisplay) { %}
        {% if (m.isCurrent && (engineType === 'GAS' || engineType === 'ECO')) { %}
            <span>Not Available</span>
        {% } else { %}
            <span>
                    <span>Click here to select</span>
            </span>
        {% } %}
 {% } %}

我认为您的第一个实现是正确的。将逻辑放在视图之外。 "correct" 方式或 "backbone" 方式是将逻辑保持在需要的位置:

  1. model/collection 代码 "where" 数据需要来自。
  2. "what" 的视图房屋代码需要 do/display。 (如果事件 X 发生需要发生什么)
  3. 模板应该包含"how"需要显示的代码。

我确定我遗漏了一些东西..我会等到评论告诉我我错了然后我会更正它。

-薄纱