在emberjs上设计自定义组件/视图

时间:2012-11-16 19:22:15

标签: ember.js

我在Ember上遇到麻烦,我确信这是因为我还没有完全掌握“做事情的Ember方式”,而我正试图做一些事情。超出了标准教程的范围。

我正在开发某种textfield-with-suggestions组件,该组件将出现在我的Web应用程序的每个页面中。我不会在这里询问有关如何做到这一切的所有细节,而只是我从一开始就遇到的一些具体问题。以下是我到目前为止的相关代码片段。

// handlebars template: searchbar.hbs
{{view App.SearchField viewName="searchField"}}
<div class="results" {{bindAttr class="searchField.hasFocus"}}>
  This is where the results for whatever the user has typed are shown.
</div>

// coffeescript source of the views: searchbar.coffee
App.SearchBar: Ember.View.extend
  templateName: 'searchbar'

App.SearchField: Ember.TextField.extend
  placeholder: 'Search'
  hasFocus: false
  eventManager: Ember.Object.create
    focusIn: (event, view) ->
      @set('hasFocus', true)
    focusOut: (event, view) ->
      @set('hasFocus', false)

// somewhere in the layout of the pages in my app
<div id="header">
  {{App.SearchBar}}
</div>

这可能还需要一个控制器,但我还没有开发它,因为我还不知道它在这个设置中的适用范围。

首先,我希望在搜索字段获得焦点后立即显示建议弹出式面板。这就是我上面尝试在搜索字段上实现hasFocus属性的原因。但是如何让我的div.results面板对输入字段的焦点状态作出反应?

总的来说,这是我的问题的核心,如何连接所有东西来开发这个组件?如果答案是通过将其附加到控制器,那么如何为该组件设置控制器,以及如何指定它是它的控制器,以便它充当所有内容的上下文?

1 个答案:

答案 0 :(得分:1)

我认为你必须明确区分问题。与视图相关的东西(即用jquery操作DOM)应保留在视图中。与应用程序状态相关的东西应该在控制器中。但是,在您的情况下,我认为您可以简单地在hasFocus属性上绑定观察者,并显示建议。类似的东西:

App.SearchField: Ember.TextField.extend
  placeholder: 'Search'
  hasFocus: false
  eventManager: Ember.Object.create
    focusIn: (event, view) ->
      @set('hasFocus', true)
    focusOut: (event, view) ->
      @set('hasFocus', false)

  focusDidChange: (->
    if @hasFocus 
      $('.results')... // here I let you do the suggestion stuff 
                       // based on data retrieved from the controller
    else
       // probably hide the results div.
  ).observes('hasFocus')