【问题标题】:How to persist status messages/icons/notifications through Backbone View render?如何通过 Backbone View 渲染持久化状态消息/图标/通知?
【发布时间】:2013-05-01 07:16:01
【问题描述】:

我在视图后面的模型上调用了 save()destroy() 方法,当它们成功或失败时,它们都会在视图/模板中显示某种 UI 更改(或“通知”);也许它是成功保存的绿色复选标记,删除失败的红色 X 等。

但是,这些save()destroy() 方法也可以直接通过render() 调用或通过在成功保存或删除时更改模型上的属性间接重新渲染视图。

当然,重新渲染会清除这些 UI 通知,实质上是将 View 重置为“中性”的预保存/删除状态。

是否有一种被广泛接受的方式来通过重新渲染来持久化这类 UI 通知?或者,有没有办法部分渲染视图/模板也可以解决这个问题?

【问题讨论】:

    标签: javascript jquery backbone.js marionette


    【解决方案1】:

    状态可以是模型的一个属性,它会在重新渲染后反映在模板中,例如在您的视图模板中,类似于:

    <div class="notification notification-<%= status %>>
       <%= getStatusMessage(status) %> (Or whatever, you get the idea, perhaps
                                        status itself is an object with a message)
    </div>
    

    通过这种方式,状态消息将被烘焙到相同的重新渲染逻辑中。

    model.set("status", "error"); // re-render with error message
    model.set("status", "success"); // re-render with success message
    

    或者,视图可能会维护自己的通知。假设视图保留一个通知,您可能会执行以下操作:

    var MyView = Backbone.View.extend({
      notify: function (message, status) {
        this.notification = {message: message, status: status};
        this.render();
      },
    
      // and when rendering the template, just merge it into the data
      render: function () {
        var html = myTemplate({notification: this.notification, ...});
        //...
      }
    });
    

    在模板中:

    <% if ("undefined" !== typeof notification) { %>
      <div class="notification notification-<%= notification.status %>>
        <%= notification.message %>
      </div>
    <% }; %>
    

    然后回到你的代码中,例如:

    model.save({
      success: function () { view.notify(someMessage, "success") },
      error: function () { view.notify(someMessage, "error") }
    });
    

    【讨论】:

    • 不错的解决方案,但我确实倾向于在模型上设置非数据属性时有点畏缩,因为状态消息在技术上不是模型数据。这实际上只是针对最终用户的通知。
    • 我喜欢你添加的第二个选项;将通知保留在模型和视图/模板之外,这更有意义。谢谢!
    • 这是我在视图中经常使用的一种模式,通过混合助手并在渲染时调整模型属性,将它们几乎视为视图模型。我认为往往工作得很好,尽管复合视图模式也有优点(用于多个模型和其他数据片段(如状态消息)的视图的容器视图)。 Marionette 做得很好,可能会提供一些想法。
    【解决方案2】:

    在我看来,这更多的是您的render() 逻辑问题。如果在渲染视图时,状态消息应该持续存在,那么您的渲染方法不应该影响该 div。

    显然,这在 DOM 和视图的 $el 属性中可能会有些混乱,但您可能会想要这样的东西。

    查看

    notificationDiv : null,
    contentDiv : null,
    
    initialize : function() {
        // set up your notification and content divs here
        this.$el.append(this.notificationDiv).append(this.contentDiv);
    }, 
    
    render : function() {
        // have render only affect the content div, maybe something like this
        this.contentDiv.html( howeverYouWantToTemplate({content}) );
    },
    
    setStatus : function(status) {
        this.notificationDiv.text(status);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多