2013-04-04 49 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