2014-05-01 40 views
2

我正在創建一個按鈕組件,該按鈕組件在點擊時具有加載組件inspired by this fiddle here燼中不同狀態的自定義按鈕

以下車把顯示了組件:

{{#if 'hasSpinner'}} 
    <span class="spinner fa-spin icon-refresh"></span> 
{{/if}} 
{{#if 'hasFailureCross'}} 
    <span class="failure-cross glyphicon glyphicon-remove"></span> 
{{/if}} 
{{#if 'hasSuccessTick'}} 
    <span class="success-tick glyphicon glyphicon-ok"></span> 
{{/if}} 
{{buttonText}} 

,這是組件類:

// shows a button with a spinner 
App.AppButtonProgressComponent = Em.Component.extend({ 
    //defaults 
    buttonType: 'btn-default', 

    //you can choose whether or not to have the following elements 
    hasSpinner: true, 
    hasFailureCross: false, 
    hasSuccessCross: false, 

    //when these are active, the css kicks in and adds the icons to the button 
    spinner: false, 
    failureCross: false, 
    successTick: false, 

    actions: { 
     click: function() { 
      this.set('spinner', true); 
      this.sendAction(); 
     }, 
     showFailure: function() { 
      console.log('should show cross or something'); 
      this.set('spinner', false); 
      this.set('failureCross', true); 
     }, 
     showSuccess: function() { 
      console.log('should show success'); 
      this.set('spinner', false); 
      this.set('successTick', true); 
     }, 
     reset: function() { 
      this.set('spinner', false); 
      this.set('successTick', false); 
      this.set('failureCross', false); 
     } 
    }, 
    tagName: 'button', 
    classNames: ['btn'], 
    classNameBindings: ['buttonType', 'spinner', 'failureCross', 'successTick'] 
}); 

處理的狀態,因此是實現在父視圖控制器的狀態變量的問題。我將如何從組件外部調用這些函數中的每一個?說按鈕是否被點擊,設置微調爲真,並導致加載符號,如果向控制器冒出的請求失敗或成功,我將如何調用組件的showSuccessshowFailure方法。

我的理解錯誤嗎?有沒有更好的方法來實現這一目標?

更新:我仍在研究組件,並打算向公衆發佈已測試和已完成的元素。

回答

1

組件是單向設備。這就是說,你可以發送你的sendAction參數,並依靠這個動作進行回調。這將責任置於父母行爲上,但它允許您在適當的時候與您的組件進行交互。

我創建了一個你創建的虛擬版本,並修改了一些東西來顯示這個概念。

showFailure: function() { 
     console.log('should show cross or something'); 
     this.set('spinner', false); 

     this.set('failureCross', true); 
    }, 
    showSuccess: function() { 
     console.log('should show success'); 
     this.set('spinner', false); 
     this.set('successTick', true); 
    }, 
    reset: function() { 
     this.set('spinner', false); 
     this.set('successTick', false); 
     this.set('failureCross', false); 
    }, 
    actions:{ 
     click: function() { 
     var self = this; 
      this.set('spinner', true); 

     this.sendAction('action', 
      function(){ self.showFailure(); }, 
      function(){ self.showSuccess(); }, 
      function(){ self.reset(); } 
         ); 
    } 

然後在臨危回調

actions:{ 
    doit: function(failure, success, reset){ 
     Ember.run.later(function(){ 
     // call reject 1 second later for visual effects 
     // as if we made a call to the server 
     failure(); 
     }, 1000); 
    } 
    } 

http://emberjs.jsbin.com/qumupaxa/1/edit

父行動