状态可以是模型的一个属性,它会在重新渲染后反映在模板中,例如在您的视图模板中,例如:
<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") }
});