问题
I have Handlebars view with the following search input field:
{{view Ember.TextField valueBinding="controller.query" action="submit"}}
when a user presses 'Enter' from the search input field, we make a call to an external API, get response, and query the results accordingly. Here is the code of the (simplified) version of the controller:
App.ProductsController = Ember.ArrayController.extend({
submit: function(query) {
// call to external api
// get response
// update some values
}
});
How do we trigger "submit" function on the keyUp event instead of 'Enter'? In other words, can the "submit" function in the controller be re-run every time user adds or removes a character from the input field?
回答1:
going by this, i think you could add
keyUp: function(evt) {
this.get('controller').send('submit');
}
or maybe
keyUp: function(evt) {
this.get('controller').send('submit', this.get('controller.query'));
}
to your view (or rather a view extending Ember.TextField).
another possibility might be to work with {{action "submit" controller.query on="keyUp"}}, but i'm not quite sure how to combine that with the {{view}} helper.
回答2:
If you use
hbs:
{{view Ember.TextField valueBinding="controller.query"
action="submit" class="my-input"}}
then in the view you need to subscribe to keyUp event. Since events fire up on whole view (in this case only for elements that support this type of event, inputs, content editable, etc inside the view), you need to check for the input you are looking for.
js:
App.ProductsView = Ember.View.extend({
keyUp: function (e) {
if ($(e.target).hasClass('my-input')) { // you can use other identifier
this.get('controller').submit(e.target.value);
}
}
});
Another idea is to extend Ember.TextField class:
hbs:
{{view App.ProductTextField valueBinding="controller.query"
action="submit"}}
js:
App.ProductTextField = Ember.TextField.extend({
keyUp: function (e) {
this.get('controller').submit(e.target.value);
}
});
Actually you don't need to pass parameter to submit method from view, since controller has this information already up to date in query variable.
来源:https://stackoverflow.com/questions/15801118/ember-textfield-submit-on-keyup-event