2013-04-04 96 views
2

如何呈現Twitter引導警報?假設對於應用程序,只有一個警報容器/閃存消息。如何呈現引導警報

我希望在出現錯誤時顯示它。現在我使用一個非常骯髒的解決方案,爲控制器添加存在。

Sks.KudoController = Ember.ObjectController.extend 
    needs: ['currentUser'] 
    addKudo: (user) -> 
    self = this 
    token = $('meta[name="csrf-token"]').attr('content') 
    ErrorMessageTmplt = """ 
     <div id="kudos-flash" class="alert" alert-error" style="display: none"> 
     <a class="close" data-dismiss="alert" href="#">&times;</a> 
     <strong>oops! an error occured!</strong> 
     </div> 
    """ 
    $flashContainer = jQuery '#flash-container' 

    jQuery.post("/kudos", user_id: user.get("id"), authenticity_token: token) 
    .done((data, status) -> 
     kudosLeft = self.get 'controllers.currentUser.kudosLeft' 
     if kudosLeft > 0 
     self.decrementProperty "controllers.currentUser.kudosLeft" 
     else 
     $flashContainer.empty() 
     jQuery(ErrorMessageTmplt).appendTo($flashContainer).show() 
    ) 
    .fail((data, status) -> 
     $flashContainer.empty() 
     jQuery(ErrorMessageTmplt).appendTo($flashContainer).show() 
    ) 

我認爲它應該呈現在應用程序模板的某處,但我不知道如何。也許警報應該是一個部分?

回答

2

您可以將警報HTML代碼添加到您的應用程序模板:

<div id="flash" class="alert alert-success"> 
    <button type="button" class="close" data-dismiss="alert">&times;</button> 
    <span></span> 
</div> 

然後每個動作,你可以調用jQuery和填充一個texthtml跨度,就像這樣:

App.ProductRemoveRoute = Em.Route.extend({ 
    setupController: function(controller, model) { 
     var c = this.controllerFor('product'); 
     controller.set('content', c.get('content')); 
    }, 
    events: { 
     confirmRemove: function(record) { 
      record.deleteRecord(); 

      // I know this looks no good, and definitely has 
      // room for improvement but gets the flash going 
      $("#flash span").text("Product successfully removed.") 
      .show().parent().fadeIn() 
      .delay(2000).fadeOut('slow', function() { 
       $("#flash span").text('') 
      }); 

      this.transitionTo('products'); 
     } 
    } 
}); 

你可能想該div添加爲一個隱藏的元素,也可以使用Ember的查看didInsertElement來隱藏它:

App.ApplicationView = Em.View.extend({ 
    didInsertElement: function() { 
     this.$('#flash').hide(); 
    } 
}); 

這裏有一個小提琴:

http://jsfiddle.net/schawaska/aMGFC/(舊)

http://jsfiddle.net/schawaska/FYvuD/(新)

由於這一新樣本的,我使用的是虛擬混入擦除的通知文本,也就是現在在ApplicationController的屬性中,並且通知Flash是部分視圖模板。

這顯然不是唯一的解決方法,它更像是一個實驗/樣本,可以做什麼來刷新通知消息。再次,我確信這可以以更優雅和模塊化的方式實現。希望能幫助到你。

+0

謝謝,但我還有一個問題。你爲什麼不處理像控制器中的「刪除」操作,而是將它發送到路由?這是一個Ember公約嗎?我在哪裏可以更多地瞭解它? – wryrych 2013-04-05 06:59:49

+0

@ Wojtek'rrh'Ryrych這不需要在路線中處理,本來可以在控制器中完成,沒有問題,我只是想在刪除記錄後馬上過渡,儘管我可以使用這個。在控制器中獲得('target')。transitionTo('some.route')'。這是一個真正的選擇問題。你可以閱讀更多關於事件[這裏](http://emberjs.com/guides/templates/actions/#toc_target-bubbling)。只需在您的應用程序中就處理事件的位置保持一致。 – MilkyWayJoe 2013-04-05 14:00:40