2014-10-29 65 views
0

在我Ember.js應用程序,我有一個這樣的搜索文本字段:時刻關注Ember.TextField

{{view Ember.TextField valueBinding="search" action="doSearch" autofocus="autofocus"}} 
<button {{action "doSearch"}} type="button">Hledat</button> 

,並像下面這樣的控制器:

App.BooksController = Ember.ArrayController.extend({ 

    queryParams: ['keywords'], 
    keywords: [], 

    search: "", 

    actions: { 
     doSearch: function() { 
      var tokens = this.get('search').split(' '); 
      this.set('keywords', tokens); 
      this.set('search', ''); 
     } 
    } 
}); 

我需要的是什麼即使在按下按鈕或按下輸入鍵之後,此文本字段仍保持焦點。

實現該目標的正確方法是什麼?我想我需要將焦點設置回doSearch方法的輸入框。如何做到這一點?

回答

0

控制器和視圖層之間的通信可以使用Ember.Evented

這裏,我們去一個乾淨的方式來實現

您的模板:

{{view Ember.TextField valueBinding="search" class="search-field" action="doSearch" autofocus="autofocus"}} 
<button {{action "doSearch"}} type="button">Hledat</button> 

你的控制器:

App.BooksController = Ember.ArrayController.extend(Ember.Evented, { 

    queryParams: ['keywords'], 
    keywords: [], 

    search: "", 

    actions: { 
     doSearch: function() { 
      var tokens = this.get('search').split(' '); 
      this.set('keywords', tokens); 
      this.set('search', ''); 
      this.trigger('search'); 
     } 
    } 
}); 

而你的觀點:

App.BooksView = Ember.View.extend({ 
    didInsertElement: function() { 
     this.get('controller').on('search', function() { 
      $('.search-field').focus(); 
     }); 
     this._super(); 
    } 
}); 

這可能是更好的作用域的觀點

didInsertElement: function() { 
    this.get('controller').on('search', function() { 
     this.$().find('.search-field').focus(); 
    }.bind(this); 
    this._super(); 
} 
+0

出於某種原因,訪問文本字段,「搜索」處理函數被觸發n次當你第n次按下搜索按鈕時。這似乎不正確。是對的嗎? – 2014-10-30 08:19:38

+0

我會嘗試從您的模板中的字段中刪除action =「doSearch」。我保留它是因爲我不知道它是否在其他地方使用。 – 2014-10-30 13:33:22

+0

action =「doSearch」用於確保在向輸入框中輸入一些關鍵字時觸發該操作,並且只需按Enter(而不是按下按鈕)即可。即使被移除,可疑的n重觸發仍在發生。 – 2014-10-30 14:44:34