2011-12-30 40 views
8

我正在尋找關於如何從按鈕(請參閱下面的視圖和模板)觸發此視圖函數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> 

回答

12

您可以使用混入Ember.TargetActionSupport你的文本字段,當被調用執行insertNewlinetriggerAction()。見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(); 
    } 
}); 
+0

真棒,謝謝。我猜測不需要App.searchController的mixin,只能在App.SearchView上使用。 – 2011-12-30 18:38:48

+0

哦,你說得對。我更新了代碼。 – pangratz 2011-12-30 18:40:40