如何通过主干视图渲染持久化状态消息/图标/通知

How to persist status messages/icons/notifications through Backbone View render?

本文关键字:消息 状态 图标 通知 持久化 何通过 视图      更新时间:2023-09-26

我有save()destroy()方法被调用的模型,坐在一个视图后面,两者都显示某种UI变化(或"通知")内的视图/模板,当他们成功或失败;可能是绿色的复选标记表示保存成功,红色的X表示删除失败,等等。

然而,这些save()destroy()方法也可以重新呈现视图,或者直接通过render()调用,或者在成功保存或删除发生时间接通过更改模型上的属性。

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

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

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

<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") }
});

在我看来,这更多的是你的render()逻辑的问题。如果在呈现视图时,状态消息应该保持不变,那么呈现方法不应该影响该div。

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

<<p> 视图/strong>
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);
}