如何通过Backbone View渲染持久保存状态消息/图标/通知?

时间:2013-04-30 22:20:02

标签: javascript jquery backbone.js marionette

我在位于View后面的Model上调用了save()destroy()个方法,这些方法在View /模板中显示某种UI更改(或“通知”)成功还是失败;也许它是成功保存的绿色复选标记,红色X表示删除失败等等。

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

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

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

在我看来,这更像是你render()逻辑的问题而不是其他问题。如果在呈现视图时,状态消息应该保持不变,那么您的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);
}