Convert a bunch of callbacks to promises

This commit is contained in:
Robin Ward
2013-04-08 15:04:40 -04:00
parent 02bab415bd
commit 75aeb9550f
12 changed files with 134 additions and 174 deletions

View File

@ -53,23 +53,26 @@ Discourse.PreferencesController = Discourse.ObjectController.extend({
}).property(), }).property(),
save: function() { save: function() {
var _this = this, model = this.get('content'); var preferencesController = this;
this.set('saving', true); this.set('saving', true);
this.set('saved', false); this.set('saved', false);
// Cook the bio for preview // Cook the bio for preview
return model.save(function(result) { var model = this.get('content');
_this.set('saving', false); return model.save().then(function() {
if (result) { // success
if (Discourse.currentUser.id === model.get('id')) { preferencesController.set('saving', false);
Discourse.currentUser.set('name', model.get('name')); if (Discourse.currentUser.id === model.get('id')) {
} Discourse.currentUser.set('name', model.get('name'));
_this.set('content.bio_cooked', Discourse.Markdown.cook(_this.get('content.bio_raw')));
return _this.set('saved', true);
} else {
return alert('failed');
} }
preferencesController.set('content.bio_cooked',
Discourse.Markdown.cook(preferencesController.get('content.bio_raw')));
preferencesController.set('saved', true);
}, function() {
// failed to update
preferencesController.set('saving', false);
alert(Em.String.i18n('generic_error'));
}); });
}, },
@ -79,12 +82,20 @@ Discourse.PreferencesController = Discourse.ObjectController.extend({
}).property('saving'), }).property('saving'),
changePassword: function() { changePassword: function() {
var _this = this; var preferencesController = this;
if (!this.get('passwordProgress')) { if (!this.get('passwordProgress')) {
this.set('passwordProgress', '(generating email)'); this.set('passwordProgress', Em.String.i18n("user.change_password.in_progress"));
return this.get('content').changePassword(function(message) { return this.get('content').changePassword().then(function() {
_this.set('changePasswordProgress', false); // success
return _this.set('passwordProgress', "(" + message + ")"); preferencesController.setProperties({
changePasswordProgress: false,
passwordProgress: Em.String.i18n("user.change_password.success")
});
}, function() {
preferencesController.setProperties({
changePasswordProgress: false,
passwordProgress: Em.String.i18n("user.change_password.error")
});
}); });
} }
} }

View File

@ -34,15 +34,14 @@ Discourse.PreferencesEmailController = Discourse.ObjectController.extend({
}).property('saving'), }).property('saving'),
changeEmail: function() { changeEmail: function() {
var _this = this; var preferencesEmailController = this;
this.set('saving', true); this.set('saving', true);
return this.get('content').changeEmail(this.get('newEmail')).then(function() { return this.get('content').changeEmail(this.get('newEmail')).then(function() {
return _this.set('success', true); preferencesEmailController.set('success', true);
}, function() { }, function() {
/* Error // Error
*/ preferencesEmailController.set('error', true);
_this.set('error', true); preferencesEmailController.set('saving', false);
return _this.set('saving', false);
}); });
} }

View File

@ -7,26 +7,21 @@
@module Discourse @module Discourse
**/ **/
Discourse.StaticController = Discourse.Controller.extend({ Discourse.StaticController = Discourse.Controller.extend({
content: null,
loadPath: function(path) { loadPath: function(path) {
var $preloaded, text, var staticController = this;
_this = this;
this.set('content', null); this.set('content', null);
// Load from <noscript> if we have it. // Load from <noscript> if we have it.
$preloaded = $("noscript[data-path=\"" + path + "\"]"); var $preloaded = $("noscript[data-path=\"" + path + "\"]");
if ($preloaded.length) { if ($preloaded.length) {
text = $preloaded.text(); var text = $preloaded.text();
text = text.match(/<!-- preload-content: -->((?:.|[\n\r])*)<!-- :preload-content -->/); text = text.match(/<!-- preload-content: -->((?:.|[\n\r])*)<!-- :preload-content -->/);
text = text[1]; text = text[1];
return this.set('content', text); this.set('content', text);
} else { } else {
return Discourse.ajax({ return Discourse.ajax(Discourse.getURL(path + ".json")).then(function (result) {
url: Discourse.getURL("" + path + ".json"), staticController.set('content', result);
success: function(result) {
return _this.set('content', result);
}
}); });
} }
} }

View File

@ -80,18 +80,16 @@ Discourse.ActionSummary = Discourse.Model.extend({
}, },
clearFlags: function() { clearFlags: function() {
var _this = this; var actionSummary = this;
return Discourse.ajax({ return Discourse.ajax(Discourse.getURL("/post_actions/clear_flags"), {
url: Discourse.getURL("/post_actions/clear_flags"),
type: "POST", type: "POST",
data: { data: {
post_action_type_id: this.get('id'), post_action_type_id: this.get('id'),
id: this.get('post.id') id: this.get('post.id')
},
success: function(result) {
_this.set('post.hidden', result.hidden);
return _this.set('count', 0);
} }
}).then(function(result) {
actionSummary.set('post.hidden', result.hidden);
actionSummary.set('count', 0);
}); });
}, },

View File

@ -168,12 +168,9 @@ Discourse.Topic = Discourse.Model.extend({
}, },
// Reset our read data for this topic // Reset our read data for this topic
resetRead: function(callback) { resetRead: function() {
return Discourse.ajax(Discourse.getURL("/t/") + (this.get('id')) + "/timings", { return Discourse.ajax(Discourse.getURL("/t/") + (this.get('id')) + "/timings", {
type: 'DELETE', type: 'DELETE'
success: function() {
return typeof callback === "function" ? callback() : void 0;
}
}); });
}, },

View File

@ -126,12 +126,11 @@ Discourse.User = Discourse.Model.extend({
Save's this user's properties over AJAX via a PUT request. Save's this user's properties over AJAX via a PUT request.
@method save @method save
@param {Function} finished Function called on completion of AJAX call @returns {Promise} the result of the operation
@returns The result of finished(true) on a success, the result of finished(false) on an error
**/ **/
save: function(finished) { save: function() {
var _this = this; var user = this;
Discourse.ajax(Discourse.getURL("/users/") + this.get('username').toLowerCase(), { return Discourse.ajax(Discourse.getURL("/users/") + this.get('username').toLowerCase(), {
data: this.getProperties('auto_track_topics_after_msecs', data: this.getProperties('auto_track_topics_after_msecs',
'bio_raw', 'bio_raw',
'website', 'website',
@ -143,13 +142,10 @@ Discourse.User = Discourse.Model.extend({
'new_topic_duration_minutes', 'new_topic_duration_minutes',
'external_links_in_new_tab', 'external_links_in_new_tab',
'enable_quoting'), 'enable_quoting'),
type: 'PUT', type: 'PUT'
success: function() { }).then(function() {
Discourse.set('currentUser.enable_quoting', _this.get('enable_quoting')); Discourse.set('currentUser.enable_quoting', user.get('enable_quoting'));
Discourse.set('currentUser.external_links_in_new_tab', _this.get('external_links_in_new_tab')); Discourse.set('currentUser.external_links_in_new_tab', user.get('external_links_in_new_tab'));
return finished(true);
},
error: function() { return finished(false); }
}); });
}, },
@ -157,28 +153,15 @@ Discourse.User = Discourse.Model.extend({
Changes the password and calls the callback function on AJAX.complete. Changes the password and calls the callback function on AJAX.complete.
@method changePassword @method changePassword
@param {Function} callback Function called on completion of AJAX call @returns {Promise} the result of the change password operation
@returns The result of the callback() function on complete
**/ **/
changePassword: function(callback) { changePassword: function() {
var good; return Discourse.ajax(Discourse.getURL("/session/forgot_password"), {
good = false;
Discourse.ajax({
url: Discourse.getURL("/session/forgot_password"),
dataType: 'json', dataType: 'json',
data: { data: {
username: this.get('username') username: this.get('username')
}, },
type: 'POST', type: 'POST'
success: function() { good = true; },
complete: function() {
var message;
message = "error";
if (good) {
message = "email sent";
}
return callback(message);
}
}); });
}, },
@ -206,29 +189,24 @@ Discourse.User = Discourse.Model.extend({
@returns A stream of the user's actions containing the action of id @returns A stream of the user's actions containing the action of id
**/ **/
loadUserAction: function(id) { loadUserAction: function(id) {
var stream, var user = this;
_this = this; var stream = this.get('stream');
stream = this.get('stream'); return Discourse.ajax({
Discourse.ajax({
url: Discourse.getURL("/user_actions/") + id + ".json", url: Discourse.getURL("/user_actions/") + id + ".json",
dataType: 'json', dataType: 'json',
cache: 'false', cache: 'false'
success: function(result) { }).then(function(result) {
if (result) { if (result) {
var action;
if ((_this.get('streamFilter') || result.action_type) !== result.action_type) { if ((user.get('streamFilter') || result.action_type) !== result.action_type) return;
return;
}
action = Em.A(); var action = Em.A();
action.pushObject(Discourse.UserAction.create(result)); action.pushObject(Discourse.UserAction.create(result));
action = Discourse.UserAction.collapseStream(action); action = Discourse.UserAction.collapseStream(action);
_this.set('totalItems', _this.get('totalItems') + 1); user.set('totalItems', user.get('totalItems') + 1);
return stream.insertAt(0, action[0]); return stream.insertAt(0, action[0]);
}
} }
}); });
}, },
@ -237,39 +215,28 @@ Discourse.User = Discourse.Model.extend({
Loads more user actions, and then calls a callback if defined. Loads more user actions, and then calls a callback if defined.
@method loadMoreUserActions @method loadMoreUserActions
@param {String} callback Called after completion, on success of AJAX call, if it is defined @returns {Promise} the content of the user actions
@returns the result of the callback
**/ **/
loadMoreUserActions: function(callback) { loadMoreUserActions: function() {
var stream, url, var user = this;
_this = this; var stream = user.get('stream');
stream = this.get('stream');
if (!stream) return; if (!stream) return;
url = Discourse.getURL("/user_actions?offset=") + this.get('totalItems') + "&user_id=" + (this.get("id")); var url = Discourse.getURL("/user_actions?offset=") + this.get('totalItems') + "&user_id=" + (this.get("id"));
if (this.get('streamFilter')) { if (this.get('streamFilter')) {
url += "&filter=" + (this.get('streamFilter')); url += "&filter=" + (this.get('streamFilter'));
} }
return Discourse.ajax({ return Discourse.ajax(url, { cache: 'false' }).then( function(result) {
url: url, if (result && result.user_actions && result.user_actions.each) {
dataType: 'json', var copy = Em.A();
cache: 'false', result.user_actions.each(function(i) {
success: function(result) { return copy.pushObject(Discourse.UserAction.create(i));
var copy; });
if (result && result.user_actions && result.user_actions.each) { copy = Discourse.UserAction.collapseStream(copy);
copy = Em.A(); stream.pushObjects(copy);
result.user_actions.each(function(i) { user.set('stream', stream);
return copy.pushObject(Discourse.UserAction.create(i)); user.set('totalItems', user.get('totalItems') + result.user_actions.length);
});
copy = Discourse.UserAction.collapseStream(copy);
stream.pushObjects(copy);
_this.set('stream', stream);
_this.set('totalItems', _this.get('totalItems') + result.user_actions.length);
}
if (callback) {
return callback();
}
} }
}); });
}, },

View File

@ -41,7 +41,7 @@
<div class="control-group"> <div class="control-group">
<label class="control-label">{{i18n user.password.title}}</label> <label class="control-label">{{i18n user.password.title}}</label>
<div class="controls"> <div class="controls">
<a href="#" {{action changePassword target="controller"}} class='btn'>{{i18n user.change_password}}</a> {{controller.passwordProgress}} <a href="#" {{action changePassword target="controller"}} class='btn'>{{i18n user.change_password.action}}</a> {{controller.passwordProgress}}
</div> </div>
</div> </div>

View File

@ -241,13 +241,10 @@ Discourse.CreateAccountView = Discourse.ModalBodyView.extend({
}).property('accountPassword'), }).property('accountPassword'),
fetchConfirmationValue: function() { fetchConfirmationValue: function() {
var _this = this; var createAccountView = this;
return Discourse.ajax({ return Discourse.ajax(Discourse.getURL('/users/hp.json')).then(function (json) {
url: Discourse.getURL('/users/hp.json'), createAccountView.set('accountPasswordConfirm', json.value);
success: function(json) { createAccountView.set('accountChallenge', json.challenge.split("").reverse().join(""));
_this.set('accountPasswordConfirm', json.value);
return _this.set('accountChallenge', json.challenge.split("").reverse().join(""));
}
}); });
}, },

View File

@ -29,12 +29,12 @@ Discourse.SearchView = Discourse.View.extend({
}); });
}, },
searchPlaceholder: (function() { searchPlaceholder: function() {
return Em.String.i18n("search.placeholder"); return Em.String.i18n("search.placeholder");
}).property(), }.property(),
// If we need to perform another search // If we need to perform another search
newSearchNeeded: (function() { newSearchNeeded: function() {
this.set('noResults', false); this.set('noResults', false);
var term = this.get('term'); var term = this.get('term');
if (term && term.length >= Discourse.SiteSettings.min_search_term_length) { if (term && term.length >= Discourse.SiteSettings.min_search_term_length) {
@ -44,16 +44,16 @@ Discourse.SearchView = Discourse.View.extend({
this.set('results', null); this.set('results', null);
} }
return this.set('selectedIndex', 0); return this.set('selectedIndex', 0);
}).observes('term', 'typeFilter'), }.observes('term', 'typeFilter'),
showCancelFilter: (function() { showCancelFilter: function() {
if (this.get('loading')) return false; if (this.get('loading')) return false;
return this.present('typeFilter'); return this.present('typeFilter');
}).property('typeFilter', 'loading'), }.property('typeFilter', 'loading'),
termChanged: (function() { termChanged: function() {
return this.cancelType(); return this.cancelType();
}).observes('term'), }.observes('term'),
// We can re-order them based on the context // We can re-order them based on the context
content: (function() { content: (function() {
@ -88,26 +88,17 @@ Discourse.SearchView = Discourse.View.extend({
return this.set('loading', false); return this.set('loading', false);
}).observes('results'), }).observes('results'),
searchTerm: function(term, typeFilter) { searchTerm: Discourse.debouncePromise(function(term, typeFilter) {
var _this = this; var searchView = this;
if (this.currentSearch) { return Discourse.ajax(Discourse.getURL('/search'), {
this.currentSearch.abort(); data: {
this.currentSearch = null; term: term,
} type_filter: typeFilter
this.searcher = this.searcher || Discourse.debounce(function(term, typeFilter) { }
_this.currentSearch = Discourse.ajax({ }).then(function(results) {
url: Discourse.getURL('/search'), searchView.set('results', results);
data: { });
term: term, }, 300),
type_filter: typeFilter
},
success: function(results) {
return _this.set('results', results);
}
});
}, 300);
return this.searcher(term, typeFilter);
},
resultCount: (function() { resultCount: (function() {
var count; var count;

View File

@ -148,7 +148,7 @@ Discourse.TopicView = Discourse.View.extend(Discourse.Scrolling, {
this.get('controller').unsubscribe(); this.get('controller').unsubscribe();
var topicView = this; var topicView = this;
this.get('topic').resetRead(function() { this.get('topic').resetRead().then(function() {
topicView.set('controller.message', Em.String.i18n("topic.read_position_reset")); topicView.set('controller.message', Em.String.i18n("topic.read_position_reset"));
topicView.set('controller.loaded', false); topicView.set('controller.loaded', false);
}); });

View File

@ -13,26 +13,26 @@ Discourse.UserStreamView = Discourse.View.extend(Discourse.Scrolling, {
userBinding: 'controller.content', userBinding: 'controller.content',
scrolled: function(e) { scrolled: function(e) {
var $userStreamBottom, docViewBottom, docViewTop, position, windowHeight,
_this = this; var $userStreamBottom = $('#user-stream-bottom');
$userStreamBottom = $('#user-stream-bottom'); if ($userStreamBottom.data('loading')) return;
if ($userStreamBottom.data('loading')) {
return; var position = $userStreamBottom.position();
} if (!($userStreamBottom && position)) return;
if (!($userStreamBottom && (position = $userStreamBottom.position()))) {
return; var docViewTop = $(window).scrollTop();
} var windowHeight = $(window).height();
docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + windowHeight;
windowHeight = $(window).height();
docViewBottom = docViewTop + windowHeight;
this.set('loading', true); this.set('loading', true);
if (position.top < docViewBottom) { if (position.top < docViewBottom) {
$userStreamBottom.data('loading', true); $userStreamBottom.data('loading', true);
this.set('loading', true); this.set('loading', true);
return this.get('controller.content').loadMoreUserActions(function() {
_this.set('loading', false); var userStreamView = this;
return Em.run.next(function() { return this.get('controller.content').loadMoreUserActions().then(function() {
return $userStreamBottom.data('loading', null); userStreamView.set('loading', false);
Em.run.next(function() {
$userStreamBottom.data('loading', null);
}); });
}); });
} }
@ -44,9 +44,9 @@ Discourse.UserStreamView = Discourse.View.extend(Discourse.Scrolling, {
}, },
didInsertElement: function() { didInsertElement: function() {
var _this = this; var userSteamView = this;
Discourse.MessageBus.subscribe("/users/" + (this.get('user.username').toLowerCase()), function(data) { Discourse.MessageBus.subscribe("/users/" + (this.get('user.username').toLowerCase()), function(data) {
_this.get('user').loadUserAction(data); userSteamView.get('user').loadUserAction(data);
}); });
this.bindScrolling(); this.bindScrolling();
} }

View File

@ -63,12 +63,17 @@ en:
activity_stream: "Activity" activity_stream: "Activity"
preferences: "Preferences" preferences: "Preferences"
bio: "About me" bio: "About me"
change_password: "change"
invited_by: "Invited By" invited_by: "Invited By"
trust_level: "Trust Level" trust_level: "Trust Level"
external_links_in_new_tab: "Open all external links in a new tab" external_links_in_new_tab: "Open all external links in a new tab"
enable_quoting: "Enable quote reply for highlighted text" enable_quoting: "Enable quote reply for highlighted text"
change_password:
action: "change"
success: "(email sent)"
in_progress: "(sending email)"
error: "(error)"
change_username: change_username:
action: "change" action: "change"
title: "Change Username" title: "Change Username"