2014-10-29 69 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