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(),
save: function() {
var _this = this, model = this.get('content');
var preferencesController = this;
this.set('saving', true);
this.set('saved', false);
// Cook the bio for preview
return model.save(function(result) {
_this.set('saving', false);
if (result) {
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');
var model = this.get('content');
return model.save().then(function() {
// success
preferencesController.set('saving', false);
if (Discourse.currentUser.id === model.get('id')) {
Discourse.currentUser.set('name', model.get('name'));
}
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'),
changePassword: function() {
var _this = this;
var preferencesController = this;
if (!this.get('passwordProgress')) {
this.set('passwordProgress', '(generating email)');
return this.get('content').changePassword(function(message) {
_this.set('changePasswordProgress', false);
return _this.set('passwordProgress', "(" + message + ")");
this.set('passwordProgress', Em.String.i18n("user.change_password.in_progress"));
return this.get('content').changePassword().then(function() {
// success
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'),
changeEmail: function() {
var _this = this;
var preferencesEmailController = this;
this.set('saving', true);
return this.get('content').changeEmail(this.get('newEmail')).then(function() {
return _this.set('success', true);
preferencesEmailController.set('success', true);
}, function() {
/* Error
*/
_this.set('error', true);
return _this.set('saving', false);
// Error
preferencesEmailController.set('error', true);
preferencesEmailController.set('saving', false);
});
}

View File

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

View File

@ -80,18 +80,16 @@ Discourse.ActionSummary = Discourse.Model.extend({
},
clearFlags: function() {
var _this = this;
return Discourse.ajax({
url: Discourse.getURL("/post_actions/clear_flags"),
var actionSummary = this;
return Discourse.ajax(Discourse.getURL("/post_actions/clear_flags"), {
type: "POST",
data: {
post_action_type_id: this.get('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
resetRead: function(callback) {
resetRead: function() {
return Discourse.ajax(Discourse.getURL("/t/") + (this.get('id')) + "/timings", {
type: 'DELETE',
success: function() {
return typeof callback === "function" ? callback() : void 0;
}
type: 'DELETE'
});
},

View File

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

View File

@ -41,7 +41,7 @@
<div class="control-group">
<label class="control-label">{{i18n user.password.title}}</label>
<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>

View File

@ -241,13 +241,10 @@ Discourse.CreateAccountView = Discourse.ModalBodyView.extend({
}).property('accountPassword'),
fetchConfirmationValue: function() {
var _this = this;
return Discourse.ajax({
url: Discourse.getURL('/users/hp.json'),
success: function(json) {
_this.set('accountPasswordConfirm', json.value);
return _this.set('accountChallenge', json.challenge.split("").reverse().join(""));
}
var createAccountView = this;
return Discourse.ajax(Discourse.getURL('/users/hp.json')).then(function (json) {
createAccountView.set('accountPasswordConfirm', json.value);
createAccountView.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");
}).property(),
}.property(),
// If we need to perform another search
newSearchNeeded: (function() {
newSearchNeeded: function() {
this.set('noResults', false);
var term = this.get('term');
if (term && term.length >= Discourse.SiteSettings.min_search_term_length) {
@ -44,16 +44,16 @@ Discourse.SearchView = Discourse.View.extend({
this.set('results', null);
}
return this.set('selectedIndex', 0);
}).observes('term', 'typeFilter'),
}.observes('term', 'typeFilter'),
showCancelFilter: (function() {
showCancelFilter: function() {
if (this.get('loading')) return false;
return this.present('typeFilter');
}).property('typeFilter', 'loading'),
}.property('typeFilter', 'loading'),
termChanged: (function() {
termChanged: function() {
return this.cancelType();
}).observes('term'),
}.observes('term'),
// We can re-order them based on the context
content: (function() {
@ -88,26 +88,17 @@ Discourse.SearchView = Discourse.View.extend({
return this.set('loading', false);
}).observes('results'),
searchTerm: function(term, typeFilter) {
var _this = this;
if (this.currentSearch) {
this.currentSearch.abort();
this.currentSearch = null;
}
this.searcher = this.searcher || Discourse.debounce(function(term, typeFilter) {
_this.currentSearch = Discourse.ajax({
url: Discourse.getURL('/search'),
data: {
term: term,
type_filter: typeFilter
},
success: function(results) {
return _this.set('results', results);
}
});
}, 300);
return this.searcher(term, typeFilter);
},
searchTerm: Discourse.debouncePromise(function(term, typeFilter) {
var searchView = this;
return Discourse.ajax(Discourse.getURL('/search'), {
data: {
term: term,
type_filter: typeFilter
}
}).then(function(results) {
searchView.set('results', results);
});
}, 300),
resultCount: (function() {
var count;

View File

@ -148,7 +148,7 @@ Discourse.TopicView = Discourse.View.extend(Discourse.Scrolling, {
this.get('controller').unsubscribe();
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.loaded', false);
});

View File

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

View File

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