狀態可能是模型,這將後重新繪製,例如可以反映在模板的屬性在你的視圖模板中,類似於:
<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") }
});
不是一個糟糕的解決辦法,但我不傾向於在設置模型上的非數據屬性畏縮一點點,作爲狀態信息是不是技術上的模型數據。這實際上只是針對最終用戶的通知。 – 2013-04-30 22:57:56
我喜歡你添加的第二個選項;保持通知脫離模型和視圖/模板,這更有意義。謝謝! – 2013-05-01 16:17:30
這是一種我傾向於大量使用視圖的模式,通過在助手中混合並在渲染上定製模型屬性,將它們視爲幾乎像視圖模型。我認爲,雖然對於複合視圖模式(對於多個模型和其他狀態消息的其他數據視圖的容器視圖)也有優點,但它趨於工作得很好。木偶做的很好,可能會提供一些想法。 – numbers1311407 2013-05-01 16:19:52