I am trying to create a loading button component in my Ember.js application. The button should automatically get disabled when it detects that a specific XHR is made and re-enable itself when the XHR is complete. Basically, I want it to track a specific URL that I submit and change state based on that. This is what my Handlebars file currently looks like with the component:
{{loading-button trackMethod="POST" trackURL="/addItem" value="Add Item"}}
I tried accomplishing this using jQuery's .ajaxComplete()
method in my Ember application controller but I can't get the `{{loading-button}}' component to observe any property in the application controller.
init: function() {
let self = this;
// Observe all XHRs
$(document).ajaxComplete(function(event, xhr, settings) {
self.set('ajaxCompleteUrl', settings.url);
});
}
Appreciate any pointers on how I can achieve this. Thanks.
Ember component philosophy is DATA DOWN ACTIONS UP .
My scenario is similar with yours. I created a separate search button component, if the ajax is calling then set button text is 'Searching' and disable it, when ajax completed set button text is 'Search' and enable it.
search-button.js
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['col-sm-1', 'pull-right'],
onHit: null,
isSearching: false,
canNotSearch: false,
actions: {
hit() {
this.get('onHit')();
}
}
});
search-button.hbs
<button type="button" class="btn btn-primary" {{action 'hit'}} disabled={{canNotSearch}}>
<span class="glyphicon glyphicon-search"></span>
{{#if isSearching}}
{{t 'label.common.btn.searching'}}
{{else}}
{{t 'label.common.btn.search'}}
{{/if}}
</button>
xxx-controller.js
export default Ember.Controller.extend({
searchObserver: Ember.observer('isSearching', function() {
Ember.run.later( () => {
this.set('canNotSearch', this.get('isSearching'));
}, 100);
}),
actions: {
search() {
this.set('isSearching', true);
Ember.run.later(() => {
// do some ajax call(must return a promise)
this.doSearch().then(() => {
this.set('isSearching', false);
});
}, 200);
}
}
}
so, you can use your search-button
component in any template.
{{button-search canNotSearch=canNotSearch isSearching=isSearching onHit=(action 'search')}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.