2013-04-30 20 views
2

我有save(),當他們成功或失敗查看/模板內上,坐在後面的視圖模型,這兩種顯示某種UI的變化被稱爲destroy()方法(或稱「通知」);也許這是一個綠色對號一個成功保存,一個紅色的X爲失敗的刪除等如何通過Backbone View呈現持久化狀態消息/圖標/通知?

然而,這些save()destroy()方法也重新渲染視圖,可直接通過一個render()呼叫,或間接地通過改變發生成功保存或刪除時模型上的屬性。

當然,重新渲染消除了這些UI通知,實質上將視圖重置爲其「中性」預保存/刪除狀態。

是否有通過重新繪製堅持這些類型的UI通知中的一個被廣泛接受的方式是什麼?另外,有沒有辦法部分渲染視圖/模板,也可以解決這個問題?

回答

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

不是一個糟糕的解決辦法,但我不傾向於在設置模型上的非數據屬性畏縮一點點,作爲狀態信息是不是技術上的模型數據。這實際上只是針對最終用戶的通知。 – 2013-04-30 22:57:56

+0

我喜歡你添加的第二個選項;保持通知脫離模型和視圖/模板,這更有意義。謝謝! – 2013-05-01 16:17:30

+0

這是一種我傾向於大量使用視圖的模式,通過在助手中混合並在渲染上定製模型屬性,將它們視爲幾乎像視圖模型。我認爲,雖然對於複合視圖模式(對於多個模型和其他狀態消息的其他數據視圖的容器視圖)也有優點,但它趨於工作得很好。木偶做的很好,可能會提供一些想法。 – numbers1311407 2013-05-01 16:19:52

1

在我意見這是更多的是你的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); 
} 
相關問題