从按钮触发文本字段中的操作

时间:2011-12-30 17:30:44

标签: ember.js

我正在寻找有关如何从按钮触发此视图函数insertNewLine的建议(请参阅下面的视图和模板)。我猜测可能有更好的方法来构造这段代码。谢谢你的帮助。

// view
App.SearchView = Ember.TextField.extend({
  insertNewline: function() {
    var value = this.get('value');

    if (value) {
      App.productsController.search(value);
    }
  }
});

// template
<script type="text/x-handlebars">
  {{view App.SearchView placeholder="search"}}
  <button id="search-button" class="btn primary">Search</button>
</script>

1 个答案:

答案 0 :(得分:12)

您可以在TextField上使用mixin Ember.TargetActionSupport,并在调用triggerAction()时执行insertNewline。见http://jsfiddle.net/pangratz666/zc9AA/

车把:

<script type="text/x-handlebars">
    {{view App.SearchView placeholder="search" target="App.searchController" action="search"}}
    {{#view Ember.Button target="App.searchController" action="search" }}
        Search
    {{/view}}
</script>

JavaScript的:

App = Ember.Application.create({});

App.searchController = Ember.Object.create({
    searchText: '',
    search: function(){
        console.log('search for %@'.fmt( this.get('searchText') ));
    }    
});

App.SearchView = Ember.TextField.extend(Ember.TargetActionSupport, {
    valueBinding: 'App.searchController.searchText',
    insertNewline: function() {
        this.triggerAction();
    }
});