Convert all Ajax calls to use Discourse.ajax()

This commit is contained in:
Robin Ward 2013-04-01 16:28:26 -04:00
parent 5344ab2893
commit 61b5c0340e
42 changed files with 243 additions and 247 deletions

View File

@ -25,7 +25,7 @@ Discourse.AdminEmailLogsController = Ember.ArrayController.extend(Discourse.Pres
sendTestEmail: function() { sendTestEmail: function() {
var _this = this; var _this = this;
_this.set('sentTestEmail', false); _this.set('sentTestEmail', false);
$.ajax({ Discourse.ajax({
url: Discourse.getURL("/admin/email_logs/test"), url: Discourse.getURL("/admin/email_logs/test"),
type: 'POST', type: 'POST',
data: { email_address: this.get('testEmailAddress') }, data: { email_address: this.get('testEmailAddress') },

View File

@ -4,21 +4,18 @@ Discourse.AdminApi = Discourse.Model.extend({
keyExists: function(){ keyExists: function(){
var key = this.get('key') || ''; var key = this.get('key') || '';
return key && key.length === this.VALID_KEY_LENGTH; return key && key.length === this.VALID_KEY_LENGTH;
}.property('key'), }.property('key'),
generateKey: function(){ generateKey: function(){
var _this = this; var adminApi = this;
Discourse.ajax(Discourse.getURL('/admin/api/generate_key'),{type: 'POST'}).then(function (result) {
$.ajax(Discourse.getURL('/admin/api/generate_key'),{ adminApi.set('key', result.key);
type: 'POST' });
}).success(function(result){
_this.set('key', result.key);
});
} }
}); });
Discourse.AdminApi.reopenClass({ Discourse.AdminApi.reopenClass({
find: function(){ find: function() {
return this.getAjax('/admin/api'); return this.getModelAjax('/admin/api');
} }
}); });

View File

@ -20,7 +20,7 @@ Discourse.AdminDashboard.reopenClass({
**/ **/
find: function() { find: function() {
var model = Discourse.AdminDashboard.create(); var model = Discourse.AdminDashboard.create();
return $.ajax(Discourse.getURL("/admin/dashboard"), { return Discourse.ajax(Discourse.getURL("/admin/dashboard"), {
type: 'GET', type: 'GET',
dataType: 'json', dataType: 'json',
success: function(json) { success: function(json) {
@ -39,7 +39,7 @@ Discourse.AdminDashboard.reopenClass({
**/ **/
fetchProblems: function() { fetchProblems: function() {
var model = Discourse.AdminDashboard.create(); var model = Discourse.AdminDashboard.create();
return $.ajax(Discourse.getURL("/admin/dashboard/problems"), { return Discourse.ajax(Discourse.getURL("/admin/dashboard/problems"), {
type: 'GET', type: 'GET',
dataType: 'json', dataType: 'json',
success: function(json) { success: function(json) {

View File

@ -18,7 +18,7 @@ Discourse.AdminUser = Discourse.Model.extend({
deleteAllPosts: function() { deleteAllPosts: function() {
this.set('can_delete_all_posts', false); this.set('can_delete_all_posts', false);
$.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/delete_all_posts", {type: 'PUT'}); Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/delete_all_posts", {type: 'PUT'});
}, },
// Revoke the user's admin access // Revoke the user's admin access
@ -26,14 +26,14 @@ Discourse.AdminUser = Discourse.Model.extend({
this.set('admin', false); this.set('admin', false);
this.set('can_grant_admin', true); this.set('can_grant_admin', true);
this.set('can_revoke_admin', false); this.set('can_revoke_admin', false);
return $.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/revoke_admin", {type: 'PUT'}); return Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/revoke_admin", {type: 'PUT'});
}, },
grantAdmin: function() { grantAdmin: function() {
this.set('admin', true); this.set('admin', true);
this.set('can_grant_admin', false); this.set('can_grant_admin', false);
this.set('can_revoke_admin', true); this.set('can_revoke_admin', true);
$.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/grant_admin", {type: 'PUT'}); Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/grant_admin", {type: 'PUT'});
}, },
// Revoke the user's moderation access // Revoke the user's moderation access
@ -41,18 +41,18 @@ Discourse.AdminUser = Discourse.Model.extend({
this.set('moderator', false); this.set('moderator', false);
this.set('can_grant_moderation', true); this.set('can_grant_moderation', true);
this.set('can_revoke_moderation', false); this.set('can_revoke_moderation', false);
return $.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/revoke_moderation", {type: 'PUT'}); return Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/revoke_moderation", {type: 'PUT'});
}, },
grantModeration: function() { grantModeration: function() {
this.set('moderator', true); this.set('moderator', true);
this.set('can_grant_moderation', false); this.set('can_grant_moderation', false);
this.set('can_revoke_moderation', true); this.set('can_revoke_moderation', true);
$.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/grant_moderation", {type: 'PUT'}); Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/grant_moderation", {type: 'PUT'});
}, },
refreshBrowsers: function() { refreshBrowsers: function() {
$.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/refresh_browsers", {type: 'POST'}); Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/refresh_browsers", {type: 'POST'});
bootbox.alert("Message sent to all clients!"); bootbox.alert("Message sent to all clients!");
}, },
@ -60,7 +60,7 @@ Discourse.AdminUser = Discourse.Model.extend({
this.set('can_approve', false); this.set('can_approve', false);
this.set('approved', true); this.set('approved', true);
this.set('approved_by', Discourse.get('currentUser')); this.set('approved_by', Discourse.get('currentUser'));
$.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/approve", {type: 'PUT'}); Discourse.ajax(Discourse.getURL("/admin/users/") + (this.get('id')) + "/approve", {type: 'PUT'});
}, },
username_lower: (function() { username_lower: (function() {
@ -90,7 +90,7 @@ Discourse.AdminUser = Discourse.Model.extend({
_this = this; _this = this;
if (duration = parseInt(window.prompt(Em.String.i18n('admin.user.ban_duration')), 10)) { if (duration = parseInt(window.prompt(Em.String.i18n('admin.user.ban_duration')), 10)) {
if (duration > 0) { if (duration > 0) {
return $.ajax(Discourse.getURL("/admin/users/") + this.id + "/ban", { return Discourse.ajax(Discourse.getURL("/admin/users/") + this.id + "/ban", {
type: 'PUT', type: 'PUT',
data: {duration: duration}, data: {duration: duration},
success: function() { success: function() {
@ -107,7 +107,7 @@ Discourse.AdminUser = Discourse.Model.extend({
unban: function() { unban: function() {
var _this = this; var _this = this;
return $.ajax(Discourse.getURL("/admin/users/") + this.id + "/unban", { return Discourse.ajax(Discourse.getURL("/admin/users/") + this.id + "/unban", {
type: 'PUT', type: 'PUT',
success: function() { success: function() {
window.location.reload(); window.location.reload();
@ -121,7 +121,7 @@ Discourse.AdminUser = Discourse.Model.extend({
impersonate: function() { impersonate: function() {
var _this = this; var _this = this;
return $.ajax(Discourse.getURL("/admin/impersonate"), { return Discourse.ajax(Discourse.getURL("/admin/impersonate"), {
type: 'POST', type: 'POST',
data: { data: {
username_or_email: this.get('username') username_or_email: this.get('username')
@ -150,7 +150,7 @@ Discourse.AdminUser.reopenClass({
user.set('can_approve', false); user.set('can_approve', false);
return user.set('selected', false); return user.set('selected', false);
}); });
return $.ajax(Discourse.getURL("/admin/users/approve-bulk"), { return Discourse.ajax(Discourse.getURL("/admin/users/approve-bulk"), {
type: 'PUT', type: 'PUT',
data: { data: {
users: users.map(function(u) { users: users.map(function(u) {
@ -161,7 +161,7 @@ Discourse.AdminUser.reopenClass({
}, },
find: function(username) { find: function(username) {
return $.ajax({url: Discourse.getURL("/admin/users/") + username}).then(function (result) { return Discourse.ajax({url: Discourse.getURL("/admin/users/") + username}).then(function (result) {
return Discourse.AdminUser.create(result); return Discourse.AdminUser.create(result);
}) })
}, },
@ -169,7 +169,7 @@ Discourse.AdminUser.reopenClass({
findAll: function(query, filter) { findAll: function(query, filter) {
var result; var result;
result = Em.A(); result = Em.A();
$.ajax({ Discourse.ajax({
url: Discourse.getURL("/admin/users/list/") + query + ".json", url: Discourse.getURL("/admin/users/list/") + query + ".json",
data: { data: {
filter: filter filter: filter

View File

@ -19,7 +19,7 @@ Discourse.EmailLog.reopenClass({
findAll: function(filter) { findAll: function(filter) {
var result; var result;
result = Em.A(); result = Em.A();
$.ajax({ Discourse.ajax({
url: Discourse.getURL("/admin/email_logs.json"), url: Discourse.getURL("/admin/email_logs.json"),
data: { filter: filter }, data: { filter: filter },
success: function(logs) { success: function(logs) {

View File

@ -47,14 +47,14 @@ Discourse.FlaggedPost = Discourse.Post.extend({
deletePost: function() { deletePost: function() {
if (this.get('post_number') === "1") { if (this.get('post_number') === "1") {
return $.ajax(Discourse.getURL("/t/") + this.topic_id, { type: 'DELETE', cache: false }); return Discourse.ajax(Discourse.getURL("/t/") + this.topic_id, { type: 'DELETE', cache: false });
} else { } else {
return $.ajax(Discourse.getURL("/posts/") + this.id, { type: 'DELETE', cache: false }); return Discourse.ajax(Discourse.getURL("/posts/") + this.id, { type: 'DELETE', cache: false });
} }
}, },
clearFlags: function() { clearFlags: function() {
return $.ajax(Discourse.getURL("/admin/flags/clear/") + this.id, { type: 'POST', cache: false }); return Discourse.ajax(Discourse.getURL("/admin/flags/clear/") + this.id, { type: 'POST', cache: false });
}, },
hiddenClass: (function() { hiddenClass: (function() {
@ -67,7 +67,7 @@ Discourse.FlaggedPost.reopenClass({
findAll: function(filter) { findAll: function(filter) {
var result; var result;
result = Em.A(); result = Em.A();
$.ajax({ Discourse.ajax({
url: Discourse.getURL("/admin/flags/") + filter + ".json", url: Discourse.getURL("/admin/flags/") + filter + ".json",
success: function(data) { success: function(data) {
var userLookup; var userLookup;

View File

@ -28,7 +28,7 @@ Discourse.GithubCommit.reopenClass({
findAll: function() { findAll: function() {
var result; var result;
result = Em.A(); result = Em.A();
$.ajax( "https://api.github.com/repos/discourse/discourse/commits?callback=callback", { Discourse.ajax( "https://api.github.com/repos/discourse/discourse/commits?callback=callback", {
dataType: 'jsonp', dataType: 'jsonp',
type: 'get', type: 'get',
data: { per_page: 25 }, data: { per_page: 25 },

View File

@ -69,7 +69,7 @@ Discourse.Report = Discourse.Model.extend({
Discourse.Report.reopenClass({ Discourse.Report.reopenClass({
find: function(type) { find: function(type) {
var model = Discourse.Report.create({type: type}); var model = Discourse.Report.create({type: type});
$.ajax(Discourse.getURL("/admin/reports/") + type, { Discourse.ajax(Discourse.getURL("/admin/reports/") + type, {
type: 'GET', type: 'GET',
success: function(json) { success: function(json) {

View File

@ -55,7 +55,7 @@ Discourse.SiteCustomization = Discourse.Model.extend({
header: this.header, header: this.header,
override_default_style: this.override_default_style override_default_style: this.override_default_style
}; };
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/admin/site_customizations") + (this.id ? '/' + this.id : ''), url: Discourse.getURL("/admin/site_customizations") + (this.id ? '/' + this.id : ''),
data: { data: {
site_customization: data site_customization: data
@ -67,7 +67,7 @@ Discourse.SiteCustomization = Discourse.Model.extend({
destroy: function() { destroy: function() {
if (!this.id) return; if (!this.id) return;
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/admin/site_customizations/") + this.id, url: Discourse.getURL("/admin/site_customizations/") + this.id,
type: 'DELETE' type: 'DELETE'
}); });
@ -93,7 +93,7 @@ Discourse.SiteCustomization.reopenClass({
content: [], content: [],
loading: true loading: true
}); });
$.ajax({ Discourse.ajax({
url: Discourse.getURL("/admin/site_customizations"), url: Discourse.getURL("/admin/site_customizations"),
dataType: "json", dataType: "json",
success: function(data) { success: function(data) {

View File

@ -72,7 +72,7 @@ Discourse.SiteSetting = Discourse.Model.extend({
save: function() { save: function() {
// Update the setting // Update the setting
var setting = this; var setting = this;
return $.ajax(Discourse.getURL("/admin/site_settings/") + (this.get('setting')), { return Discourse.ajax(Discourse.getURL("/admin/site_settings/") + (this.get('setting')), {
data: { value: this.get('value') }, data: { value: this.get('value') },
type: 'PUT', type: 'PUT',
success: function() { success: function() {
@ -91,10 +91,10 @@ Discourse.SiteSetting.reopenClass({
**/ **/
findAll: function() { findAll: function() {
var result = Em.A(); var result = Em.A();
$.get(Discourse.getURL("/admin/site_settings"), function(settings) { Discourse.ajax({url: Discourse.getURL("/admin/site_settings")}).then(function (settings) {
return settings.each(function(s) { settings.each(function(s) {
s.originalValue = s.value; s.originalValue = s.value;
return result.pushObject(Discourse.SiteSetting.create(s)); result.pushObject(Discourse.SiteSetting.create(s));
}); });
}); });
return result; return result;

View File

@ -26,7 +26,7 @@ Discourse.VersionCheck = Discourse.Model.extend({
Discourse.VersionCheck.reopenClass({ Discourse.VersionCheck.reopenClass({
find: function() { find: function() {
return $.ajax({ url: Discourse.getURL('/admin/version_check'), dataType: 'json' }).then(function(json) { return Discourse.ajax({ url: Discourse.getURL('/admin/version_check'), dataType: 'json' }).then(function(json) {
return Discourse.VersionCheck.create(json); return Discourse.VersionCheck.create(json);
}); });
} }

View File

@ -166,7 +166,7 @@ Discourse = Ember.Application.createWithMixins({
**/ **/
logout: function() { logout: function() {
Discourse.KeyValueStore.abandonLocal(); Discourse.KeyValueStore.abandonLocal();
return $.ajax(Discourse.getURL("/session/") + this.get('currentUser.username'), { return Discourse.ajax(Discourse.getURL("/session/") + this.get('currentUser.username'), {
type: 'DELETE', type: 'DELETE',
success: function(result) { success: function(result) {
// To keep lots of our variables unbound, we can handle a redirect on logging out. // To keep lots of our variables unbound, we can handle a redirect on logging out.
@ -182,6 +182,21 @@ Discourse = Ember.Application.createWithMixins({
return loginView.authenticationComplete(options); return loginView.authenticationComplete(options);
}, },
/**
Our own $.ajax method. Makes sure the .then method executes in an Ember runloop
for performance reasons.
@method ajax
**/
ajax: function() {
return $.ajax.apply(this, arguments);
},
/**
Start up the Discourse application.
@method start
**/
start: function() { start: function() {
Discourse.bindDOMEvents(); Discourse.bindDOMEvents();
Discourse.SiteSettings = PreloadStore.get('siteSettings'); Discourse.SiteSettings = PreloadStore.get('siteSettings');

View File

@ -70,11 +70,14 @@ Discourse.ClickTrack = {
// if they want to open in a new tab, do an AJAX request // if they want to open in a new tab, do an AJAX request
if (e.metaKey || e.ctrlKey || e.which === 2) { if (e.metaKey || e.ctrlKey || e.which === 2) {
$.get(Discourse.getURL("/clicks/track"), {
url: href, Discourse.ajax(Discourse.getURL("/clicks/track"), {
post_id: postId, data: {
topic_id: topicId, url: href,
redirect: false post_id: postId,
topic_id: topicId,
redirect: false
}
}); });
window.open(href, '_blank'); window.open(href, '_blank');
return false; return false;
@ -82,11 +85,13 @@ Discourse.ClickTrack = {
// If we're on the same site, use the router and track via AJAX // If we're on the same site, use the router and track via AJAX
if (href.indexOf(window.location.origin) === 0) { if (href.indexOf(window.location.origin) === 0) {
$.get(Discourse.getURL("/clicks/track"), { Discourse.ajax(Discourse.getURL("/clicks/track"), {
url: href, data: {
post_id: postId, url: href,
topic_id: topicId, post_id: postId,
redirect: false topic_id: topicId,
redirect: false
}
}); });
Discourse.URL.routeTo(href); Discourse.URL.routeTo(href);
return false; return false;

View File

@ -6,39 +6,36 @@
@module Discourse @module Discourse
**/ **/
Discourse.Mention = (function() { Discourse.Mention = (function() {
var cache, load, localCache, lookup, lookupCache; var localCache = {};
localCache = {};
cache = function(name, valid) { var cache = function(name, valid) {
localCache[name] = valid; localCache[name] = valid;
}; };
lookupCache = function(name) {
var lookupCache = function(name) {
return localCache[name]; return localCache[name];
}; };
lookup = function(name, callback) {
var cached; var lookup = function(name, callback) {
cached = lookupCache(name); var cached = lookupCache(name);
if (cached === true || cached === false) { if (cached === true || cached === false) {
callback(cached); callback(cached);
return false; return false;
} else { } else {
$.get(Discourse.getURL("/users/is_local_username"), { Discourse.ajax(Discourse.getURL("/users/is_local_username"), { data: { username: name } }).then(function(r) {
username: name
}, function(r) {
cache(name, r.valid); cache(name, r.valid);
return callback(r.valid); callback(r.valid);
}); });
return true; return true;
} }
}; };
load = function(e) {
var $elem, loading, username; var load = function(e) {
$elem = $(e); var $elem = $(e);
if ($elem.data('mention-tested')) { if ($elem.data('mention-tested')) return;
return; var username = $elem.text();
}
username = $elem.text();
username = username.substr(1); username = username.substr(1);
loading = lookup(username, function(valid) { var loading = lookup(username, function(valid) {
if (valid) { if (valid) {
return $elem.replaceWith("<a href='" + Discourse.getURL("/users/") + (username.toLowerCase()) + "' class='mention'>@" + username + "</a>"); return $elem.replaceWith("<a href='" + Discourse.getURL("/users/") + (username.toLowerCase()) + "' class='mention'>@" + username + "</a>");
} else { } else {
@ -49,11 +46,8 @@ Discourse.Mention = (function() {
return $elem.addClass('mention-loading'); return $elem.addClass('mention-loading');
} }
}; };
return {
load: load, return { load: load, lookup: lookup, lookupCache: lookupCache };
lookup: lookup,
lookupCache: lookupCache
};
})(); })();

View File

@ -68,7 +68,7 @@ Discourse.MessageBus = (function() {
data[c.channel] = c.last_id === void 0 ? -1 : c.last_id; data[c.channel] = c.last_id === void 0 ? -1 : c.last_id;
}); });
gotData = false; gotData = false;
_this.longPoll = $.ajax(Discourse.getURL("/message-bus/") + clientId + "/poll?" + (isHidden() || !_this.enableLongPolling ? "dlp=t" : ""), { _this.longPoll = Discourse.ajax(Discourse.getURL("/message-bus/") + clientId + "/poll?" + (isHidden() || !_this.enableLongPolling ? "dlp=t" : ""), {
data: data, data: data,
cache: false, cache: false,
dataType: 'json', dataType: 'json',

View File

@ -49,7 +49,7 @@ Discourse.Onebox = {
$elem.addClass('loading-onebox'); $elem.addClass('loading-onebox');
// Retrieve the onebox // Retrieve the onebox
var promise = $.ajax({ var promise = Discourse.ajax({
type: 'GET', type: 'GET',
url: "/onebox", url: "/onebox",
data: { url: url, refresh: refresh } data: { url: url, refresh: refresh }

View File

@ -98,7 +98,7 @@ Discourse.ScreenTrack = Ember.Object.extend({
highestSeenByTopic[topicId] = this.highestSeen; highestSeenByTopic[topicId] = this.highestSeen;
} }
if (!Object.isEmpty(newTimings)) { if (!Object.isEmpty(newTimings)) {
$.ajax(Discourse.getURL('/topics/timings'), { Discourse.ajax(Discourse.getURL('/topics/timings'), {
data: { data: {
timings: newTimings, timings: newTimings,
topic_time: this.topicTime, topic_time: this.topicTime,

View File

@ -14,7 +14,7 @@ cacheTopicId = null;
cacheTime = null; cacheTime = null;
doSearch = function(term, topicId, success) { doSearch = function(term, topicId, success) {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL('/users/search/users'), url: Discourse.getURL('/users/search/users'),
dataType: 'JSON', dataType: 'JSON',
data: { data: {

View File

@ -25,15 +25,10 @@ Discourse.Utilities = {
}, },
categoryUrlId: function(category) { categoryUrlId: function(category) {
var id, slug; if (!category) return "";
if (!category) { var id = Em.get(category, 'id');
return ""; var slug = Em.get(category, 'slug');
} if ((!slug) || slug.isBlank()) return "" + id + "-category";
id = Em.get(category, 'id');
slug = Em.get(category, 'slug');
if ((!slug) || slug.isBlank()) {
return "" + id + "-category";
}
return slug; return slug;
}, },

View File

@ -132,7 +132,7 @@ Discourse.ComposerController = Discourse.Controller.extend({
// If visible update the text // If visible update the text
var educationKey = this.get('content.creatingTopic') ? 'new-topic' : 'new-reply'; var educationKey = this.get('content.creatingTopic') ? 'new-topic' : 'new-reply';
var composerController = this; var composerController = this;
$.get(Discourse.getURL("/education/") + educationKey).then(function(result) { Discourse.ajax(Discourse.getURL("/education/") + educationKey).then(function(result) {
composerController.set('educationContents', result); composerController.set('educationContents', result);
}); });
}.observes('typedReply', 'content.creatingTopic', 'Discourse.currentUser.reply_count'), }.observes('typedReply', 'content.creatingTopic', 'Discourse.currentUser.reply_count'),

View File

@ -22,7 +22,7 @@ Discourse.StaticController = Discourse.Controller.extend({
text = text[1]; text = text[1];
return this.set('content', text); return this.set('content', text);
} else { } else {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("" + path + ".json"), url: Discourse.getURL("" + path + ".json"),
success: function(result) { success: function(result) {
return _this.set('content', result); return _this.set('content', result);

View File

@ -52,7 +52,7 @@ Discourse.ActionSummary = Discourse.Model.extend({
// Create our post action // Create our post action
var actionSummary = this; var actionSummary = this;
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/post_actions"), url: Discourse.getURL("/post_actions"),
type: 'POST', type: 'POST',
data: { data: {
@ -71,7 +71,7 @@ Discourse.ActionSummary = Discourse.Model.extend({
this.removeAction(); this.removeAction();
// Remove our post action // Remove our post action
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/post_actions/") + (this.get('post.id')), url: Discourse.getURL("/post_actions/") + (this.get('post.id')),
type: 'DELETE', type: 'DELETE',
data: { data: {
@ -82,7 +82,7 @@ Discourse.ActionSummary = Discourse.Model.extend({
clearFlags: function() { clearFlags: function() {
var _this = this; var _this = this;
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/post_actions/clear_flags"), url: Discourse.getURL("/post_actions/clear_flags"),
type: "POST", type: "POST",
data: { data: {
@ -97,14 +97,17 @@ Discourse.ActionSummary = Discourse.Model.extend({
}, },
loadUsers: function() { loadUsers: function() {
var _this = this; var actionSummary = this;
return $.getJSON(Discourse.getURL("/post_actions/users"), { Discourse.ajax(Discourse.getURL("/post_actions/users"), {
id: this.get('post.id'), data: {
post_action_type_id: this.get('id') id: this.get('post.id'),
}, function(result) { post_action_type_id: this.get('id')
_this.set('users', Em.A()); }
return result.each(function(u) { }).then(function (result) {
return _this.get('users').pushObject(Discourse.User.create(u)); var users = Em.A();
actionSummary.set('users', users);
result.each(function(u) {
users.pushObject(Discourse.User.create(u));
}); });
}); });
} }

View File

@ -38,7 +38,7 @@ Discourse.Category = Discourse.Model.extend({
}, },
destroy: function(callback) { destroy: function(callback) {
return $.ajax(Discourse.getURL("/categories/") + (this.get('slug')), { type: 'DELETE' }); return Discourse.ajax(Discourse.getURL("/categories/") + (this.get('slug')), { type: 'DELETE' });
} }
}); });

View File

@ -32,7 +32,8 @@ Discourse.CategoryList.reopenClass({
list: function(filter) { list: function(filter) {
var route = this; var route = this;
return $.getJSON(Discourse.getURL("/") + filter + ".json").then(function(result) {
return Discourse.ajax(Discourse.getURL("/") + filter + ".json").then(function(result) {
var categoryList = Discourse.TopicList.create(); var categoryList = Discourse.TopicList.create();
categoryList.set('can_create_category', result.category_list.can_create_category); categoryList.set('can_create_category', result.category_list.can_create_category);
categoryList.set('categories', route.categoriesFrom(result)); categoryList.set('categories', route.categoriesFrom(result));

View File

@ -11,7 +11,7 @@ Discourse.Draft = Discourse.Model.extend({});
Discourse.Draft.reopenClass({ Discourse.Draft.reopenClass({
clear: function(key, sequence) { clear: function(key, sequence) {
return $.ajax({ return Discourse.ajax({
type: 'DELETE', type: 'DELETE',
url: Discourse.getURL("/draft"), url: Discourse.getURL("/draft"),
data: { data: {
@ -22,7 +22,7 @@ Discourse.Draft.reopenClass({
}, },
get: function(key) { get: function(key) {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL('/draft'), url: Discourse.getURL('/draft'),
data: { draft_key: key }, data: { draft_key: key },
dataType: 'json' dataType: 'json'
@ -36,7 +36,7 @@ Discourse.Draft.reopenClass({
save: function(key, sequence, data) { save: function(key, sequence, data) {
data = typeof data === "string" ? data : JSON.stringify(data); data = typeof data === "string" ? data : JSON.stringify(data);
return $.ajax({ return Discourse.ajax({
type: 'POST', type: 'POST',
url: Discourse.getURL("/draft"), url: Discourse.getURL("/draft"),
data: { data: {

View File

@ -10,7 +10,7 @@
Discourse.Invite = Discourse.Model.extend({ Discourse.Invite = Discourse.Model.extend({
rescind: function() { rescind: function() {
$.ajax(Discourse.getURL('/invites'), { Discourse.ajax(Discourse.getURL('/invites'), {
type: 'DELETE', type: 'DELETE',
data: { email: this.get('email') } data: { email: this.get('email') }
}); });

View File

@ -15,7 +15,7 @@ Discourse.InviteList = Discourse.Model.extend({
Discourse.InviteList.reopenClass({ Discourse.InviteList.reopenClass({
findInvitedBy: function(user) { findInvitedBy: function(user) {
return $.ajax({ url: Discourse.getURL("/users/") + (user.get('username_lower')) + "/invited.json" }).then(function (result) { return Discourse.ajax({ url: Discourse.getURL("/users/") + (user.get('username_lower')) + "/invited.json" }).then(function (result) {
var invitedList = result.invited_list; var invitedList = result.invited_list;
if (invitedList.pending) { if (invitedList.pending) {
invitedList.pending = invitedList.pending.map(function(i) { invitedList.pending = invitedList.pending.map(function(i) {

View File

@ -21,7 +21,7 @@ Discourse.Model = Ember.Object.extend(Discourse.Presence, {
args.error = function(xhr) { args.error = function(xhr) {
return oldError($.parseJSON(xhr.responseText).errors); return oldError($.parseJSON(xhr.responseText).errors);
}; };
return $.ajax(url, args); return Discourse.ajax(url, args);
}, },
/** /**
@ -48,36 +48,20 @@ Discourse.Model = Ember.Object.extend(Discourse.Presence, {
_this.set(k, v); _this.set(k, v);
} }
}); });
} }
}); });
Discourse.Model.reopenClass({ Discourse.Model.reopenClass({
/** /**
$.get shortcut that uses Discourse.Url and returns a promise $.get shortcut that uses Discourse.Url and returns a promise
**/ **/
getAjax: function(url) { getModelAjax: function(url) {
var _this = this; var modelClass = this;
var promise = new Ember.Deferred(); return Discourse.ajax({ url: url, cache: false, dataType: 'json' }).then(function (result) {
return modelClass.create(result);
$.ajax(Discourse.getURL(url), { });
cache: false,
type: 'GET',
dataType: 'json',
success: function(result){
promise.resolve(_this.create(result));
},
error: function(jqXHR, textStatus, errorThrown){
promise.reject({
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
});
}
});
return promise;
}, },
@ -89,15 +73,10 @@ Discourse.Model.reopenClass({
@param {Object} klass Optional The class to instantiate @param {Object} klass Optional The class to instantiate
**/ **/
extractByKey: function(collection, klass) { extractByKey: function(collection, klass) {
var retval; var retval = {};
retval = {}; if (!collection) return retval;
if (!collection) {
return retval;
}
collection.each(function(c) { collection.each(function(c) {
var obj; retval[c.id] = klass.create(c);
obj = klass.create(c);
retval[c.id] = obj;
}); });
return retval; return retval;
} }

View File

@ -68,7 +68,7 @@ Discourse.Post = Discourse.Model.extend({
bookmarkedChanged: (function() { bookmarkedChanged: (function() {
var _this = this; var _this = this;
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/posts/") + (this.get('id')) + "/bookmark", url: Discourse.getURL("/posts/") + (this.get('id')) + "/bookmark",
type: 'PUT', type: 'PUT',
data: { data: {
@ -127,7 +127,7 @@ Discourse.Post = Discourse.Model.extend({
var data, metaData; var data, metaData;
if (!this.get('newPost')) { if (!this.get('newPost')) {
// We're updating a post // We're updating a post
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/posts/") + (this.get('id')), url: Discourse.getURL("/posts/") + (this.get('id')),
type: 'PUT', type: 'PUT',
data: { data: {
@ -157,7 +157,7 @@ Discourse.Post = Discourse.Model.extend({
data.meta_data = {}; data.meta_data = {};
Ember.keys(metaData).forEach(function(key) { data.meta_data[key] = metaData.get(key); }); Ember.keys(metaData).forEach(function(key) { data.meta_data[key] = metaData.get(key); });
} }
return $.ajax({ return Discourse.ajax({
type: 'POST', type: 'POST',
url: Discourse.getURL("/posts"), url: Discourse.getURL("/posts"),
data: data, data: data,
@ -172,11 +172,11 @@ Discourse.Post = Discourse.Model.extend({
}, },
recover: function() { recover: function() {
return $.ajax(Discourse.getURL("/posts/") + (this.get('id')) + "/recover", { type: 'PUT', cache: false }); return Discourse.ajax(Discourse.getURL("/posts/") + (this.get('id')) + "/recover", { type: 'PUT', cache: false });
}, },
destroy: function(complete) { destroy: function(complete) {
return $.ajax(Discourse.getURL("/posts/") + (this.get('id')), { type: 'DELETE' }); return Discourse.ajax(Discourse.getURL("/posts/") + (this.get('id')), { type: 'DELETE' });
}, },
// Update the properties of this post from an obj, ignoring cooked as we should already // Update the properties of this post from an obj, ignoring cooked as we should already
@ -216,7 +216,7 @@ Discourse.Post = Discourse.Model.extend({
this.set('replies', []); this.set('replies', []);
var parent = this; var parent = this;
return $.ajax({url: Discourse.getURL("/posts/") + (this.get('id')) + "/replies"}).then(function(loaded) { return Discourse.ajax({url: Discourse.getURL("/posts/") + (this.get('id')) + "/replies"}).then(function(loaded) {
var replies = parent.get('replies'); var replies = parent.get('replies');
loaded.each(function(reply) { loaded.each(function(reply) {
var post = Discourse.Post.create(reply); var post = Discourse.Post.create(reply);
@ -227,10 +227,8 @@ Discourse.Post = Discourse.Model.extend({
}); });
}, },
loadVersions: function(callback) { loadVersions: function() {
return $.get(Discourse.getURL("/posts/") + (this.get('id')) + "/versions.json", function(result) { return Discourse.ajax(Discourse.getURL("/posts/") + (this.get('id')) + "/versions.json");
return callback(result);
});
}, },
// Whether to show replies directly below // Whether to show replies directly below
@ -284,7 +282,7 @@ Discourse.Post.reopenClass({
}, },
deleteMany: function(posts) { deleteMany: function(posts) {
return $.ajax(Discourse.getURL("/posts/destroy_many"), { return Discourse.ajax(Discourse.getURL("/posts/destroy_many"), {
type: 'DELETE', type: 'DELETE',
data: { data: {
post_ids: posts.map(function(p) { return p.get('id'); }) post_ids: posts.map(function(p) { return p.get('id'); })
@ -293,26 +291,26 @@ Discourse.Post.reopenClass({
}, },
loadVersion: function(postId, version, callback) { loadVersion: function(postId, version, callback) {
return $.ajax({url: Discourse.getURL("/posts/") + postId + ".json?version=" + version}).then(function(result) { return Discourse.ajax({url: Discourse.getURL("/posts/") + postId + ".json?version=" + version}).then(function(result) {
return Discourse.Post.create(result); return Discourse.Post.create(result);
}); });
}, },
loadByPostNumber: function(topicId, postId) { loadByPostNumber: function(topicId, postId) {
return $.ajax({url: Discourse.getURL("/posts/by_number/") + topicId + "/" + postId + ".json"}).then(function (result) { return Discourse.ajax({url: Discourse.getURL("/posts/by_number/") + topicId + "/" + postId + ".json"}).then(function (result) {
return Discourse.Post.create(result); return Discourse.Post.create(result);
}); });
}, },
loadQuote: function(postId) { loadQuote: function(postId) {
return $.ajax({url: Discourse.getURL("/posts/") + postId + ".json"}).then(function(result) { return Discourse.ajax({url: Discourse.getURL("/posts/") + postId + ".json"}).then(function(result) {
var post = Discourse.Post.create(result); var post = Discourse.Post.create(result);
return Discourse.BBCode.buildQuoteBBCode(post, post.get('raw')); return Discourse.BBCode.buildQuoteBBCode(post, post.get('raw'));
}); });
}, },
load: function(postId) { load: function(postId) {
return $.ajax({url: Discourse.getURL("/posts/") + postId + ".json"}).then(function (result) { return Discourse.ajax({url: Discourse.getURL("/posts/") + postId + ".json"}).then(function (result) {
return Discourse.Post.create(result); return Discourse.Post.create(result);
}); });
} }

View File

@ -20,13 +20,12 @@ Discourse.Topic = Discourse.Model.extend({
}).property('archetype'), }).property('archetype'),
convertArchetype: function(archetype) { convertArchetype: function(archetype) {
var a; var a = this.get('archetype');
a = this.get('archetype');
if (a !== 'regular' && a !== 'private_message') { if (a !== 'regular' && a !== 'private_message') {
this.set('archetype', 'regular'); this.set('archetype', 'regular');
return $.post(this.get('url'), { return Discourse.ajax(this.get('url'), {
_method: 'put', type: 'PUT',
archetype: 'regular' data: {archetype: 'regular'}
}); });
} }
}, },
@ -47,8 +46,7 @@ Discourse.Topic = Discourse.Model.extend({
// Helper to build a Url with a post number // Helper to build a Url with a post number
urlForPostNumber: function(postNumber) { urlForPostNumber: function(postNumber) {
var url; var url = this.get('url');
url = this.get('url');
if (postNumber && (postNumber > 1)) { if (postNumber && (postNumber > 1)) {
url += "/" + postNumber; url += "/" + postNumber;
} }
@ -129,10 +127,9 @@ Discourse.Topic = Discourse.Model.extend({
toggleStatus: function(property) { toggleStatus: function(property) {
this.toggleProperty(property); this.toggleProperty(property);
return $.post("" + (this.get('url')) + "/status", { return Discourse.ajax(this.get('url') + "/status", {
_method: 'put', type: 'PUT',
status: property, data: {status: property, enabled: this.get(property) ? 'true' : 'false' }
enabled: this.get(property) ? 'true' : 'false'
}); });
}, },
@ -147,7 +144,7 @@ Discourse.Topic = Discourse.Model.extend({
toggleStar: function() { toggleStar: function() {
var topic = this; var topic = this;
topic.toggleProperty('starred'); topic.toggleProperty('starred');
return $.ajax({ return Discourse.ajax({
url: "" + (this.get('url')) + "/star", url: "" + (this.get('url')) + "/star",
type: 'PUT', type: 'PUT',
data: { starred: topic.get('starred') ? true : false }, data: { starred: topic.get('starred') ? true : false },
@ -163,16 +160,16 @@ Discourse.Topic = Discourse.Model.extend({
save: function() { save: function() {
// Don't save unless we can // Don't save unless we can
if (!this.get('can_edit')) return; if (!this.get('can_edit')) return;
return $.post(this.get('url'), {
_method: 'put', return Discourse.ajax(this.get('url'), {
title: this.get('title'), type: 'PUT',
category: this.get('category.name') data: { title: this.get('title'), category: this.get('category.name') }
}); });
}, },
// Reset our read data for this topic // Reset our read data for this topic
resetRead: function(callback) { resetRead: function(callback) {
return $.ajax(Discourse.getURL("/t/") + (this.get('id')) + "/timings", { return Discourse.ajax(Discourse.getURL("/t/") + (this.get('id')) + "/timings", {
type: 'DELETE', type: 'DELETE',
success: function() { success: function() {
return typeof callback === "function" ? callback() : void 0; return typeof callback === "function" ? callback() : void 0;
@ -182,7 +179,7 @@ Discourse.Topic = Discourse.Model.extend({
// Invite a user to this topic // Invite a user to this topic
inviteUser: function(user) { inviteUser: function(user) {
return $.ajax({ return Discourse.ajax({
type: 'POST', type: 'POST',
url: Discourse.getURL("/t/") + (this.get('id')) + "/invite", url: Discourse.getURL("/t/") + (this.get('id')) + "/invite",
data: { data: {
@ -193,7 +190,7 @@ Discourse.Topic = Discourse.Model.extend({
// Delete this topic // Delete this topic
destroy: function() { destroy: function() {
return $.ajax(Discourse.getURL("/t/") + (this.get('id')), { type: 'DELETE' }); return Discourse.ajax(Discourse.getURL("/t/") + (this.get('id')), { type: 'DELETE' });
}, },
// Load the posts for this topic // Load the posts for this topic
@ -306,7 +303,7 @@ Discourse.Topic = Discourse.Model.extend({
updateNotifications: function(v) { updateNotifications: function(v) {
this.set('notification_level', v); this.set('notification_level', v);
this.set('notifications_reason_id', null); this.set('notifications_reason_id', null);
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/t/") + (this.get('id')) + "/notifications", url: Discourse.getURL("/t/") + (this.get('id')) + "/notifications",
type: 'POST', type: 'POST',
data: { data: {
@ -342,7 +339,7 @@ Discourse.Topic = Discourse.Model.extend({
// Clear the pin optimistically from the object // Clear the pin optimistically from the object
topic.set('pinned', false); topic.set('pinned', false);
$.ajax(Discourse.getURL("/t/") + this.get('id') + "/clear-pin", { Discourse.ajax(Discourse.getURL("/t/") + this.get('id') + "/clear-pin", {
type: 'PUT', type: 'PUT',
error: function() { error: function() {
// On error, put the pin back // On error, put the pin back
@ -382,7 +379,7 @@ Discourse.Topic.reopenClass({
@returns A promise that will resolve to the topics @returns A promise that will resolve to the topics
**/ **/
findSimilarTo: function(title, body) { findSimilarTo: function(title, body) {
return $.ajax({url: Discourse.getURL("/topics/similar_to"), data: {title: title, raw: body} }).then(function (results) { return Discourse.ajax({url: Discourse.getURL("/topics/similar_to"), data: {title: title, raw: body} }).then(function (results) {
return results.map(function(topic) { return Discourse.Topic.create(topic) }); return results.map(function(topic) { return Discourse.Topic.create(topic) });
}); });
}, },
@ -424,7 +421,7 @@ Discourse.Topic.reopenClass({
// Check the preload store. If not, load it via JSON // Check the preload store. If not, load it via JSON
return PreloadStore.getAndRemove("topic_" + topicId, function() { return PreloadStore.getAndRemove("topic_" + topicId, function() {
return $.getJSON(url + ".json", data); return Discourse.ajax(url + ".json", {data: data});
}).then(function(result) { }).then(function(result) {
var first = result.posts.first(); var first = result.posts.first();
if (first && opts && opts.bestOf) { if (first && opts && opts.bestOf) {
@ -436,7 +433,7 @@ Discourse.Topic.reopenClass({
// Create a topic from posts // Create a topic from posts
movePosts: function(topicId, title, postIds) { movePosts: function(topicId, title, postIds) {
return $.ajax(Discourse.getURL(Discourse.getURL("/t/")) + topicId + "/move-posts", { return Discourse.ajax(Discourse.getURL(Discourse.getURL("/t/")) + topicId + "/move-posts", {
type: 'POST', type: 'POST',
data: { title: title, post_ids: postIds } data: { title: title, post_ids: postIds }
}); });

View File

@ -14,7 +14,7 @@ Discourse.TopicList = Discourse.Model.extend({
if (moreUrl = this.get('more_topics_url')) { if (moreUrl = this.get('more_topics_url')) {
Discourse.URL.replaceState(Discourse.getURL("/") + (this.get('filter')) + "/more"); Discourse.URL.replaceState(Discourse.getURL("/") + (this.get('filter')) + "/more");
return $.ajax({url: moreUrl}).then(function (result) { return Discourse.ajax({url: moreUrl}).then(function (result) {
var newTopics, topicIds, topics, topicsAdded = 0; var newTopics, topicIds, topics, topicsAdded = 0;
if (result) { if (result) {
// the new topics loaded from the server // the new topics loaded from the server
@ -106,7 +106,9 @@ Discourse.TopicList.reopenClass({
Discourse.set('transient.topicsList', null); Discourse.set('transient.topicsList', null);
Discourse.set('transient.topicListScrollPos', null); Discourse.set('transient.topicListScrollPos', null);
return PreloadStore.getAndRemove("topic_list", function() { return $.getJSON(url) }).then(function(result) { return PreloadStore.getAndRemove("topic_list", function() {
return Discourse.ajax(url);
}).then(function(result) {
topic_list.set('topics', Discourse.TopicList.topicsFrom(result)); topic_list.set('topics', Discourse.TopicList.topicsFrom(result));
topic_list.set('can_create_topic', result.topic_list.can_create_topic); topic_list.set('can_create_topic', result.topic_list.can_create_topic);
topic_list.set('more_topics_url', result.topic_list.more_topics_url); topic_list.set('more_topics_url', result.topic_list.more_topics_url);

View File

@ -86,7 +86,7 @@ Discourse.User = Discourse.Model.extend({
@returns Result of ajax call @returns Result of ajax call
**/ **/
changeUsername: function(newUsername) { changeUsername: function(newUsername) {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/users/") + (this.get('username_lower')) + "/preferences/username", url: Discourse.getURL("/users/") + (this.get('username_lower')) + "/preferences/username",
type: 'PUT', type: 'PUT',
data: { data: {
@ -103,7 +103,7 @@ Discourse.User = Discourse.Model.extend({
@returns Result of ajax call @returns Result of ajax call
**/ **/
changeEmail: function(email) { changeEmail: function(email) {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/users/") + (this.get('username_lower')) + "/preferences/email", url: Discourse.getURL("/users/") + (this.get('username_lower')) + "/preferences/email",
type: 'PUT', type: 'PUT',
data: { data: {
@ -131,7 +131,7 @@ Discourse.User = Discourse.Model.extend({
**/ **/
save: function(finished) { save: function(finished) {
var _this = this; var _this = this;
$.ajax(Discourse.getURL("/users/") + this.get('username').toLowerCase(), { 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',
@ -163,7 +163,7 @@ Discourse.User = Discourse.Model.extend({
changePassword: function(callback) { changePassword: function(callback) {
var good; var good;
good = false; good = false;
$.ajax({ Discourse.ajax({
url: Discourse.getURL("/session/forgot_password"), url: Discourse.getURL("/session/forgot_password"),
dataType: 'json', dataType: 'json',
data: { data: {
@ -209,7 +209,7 @@ Discourse.User = Discourse.Model.extend({
var stream, var stream,
_this = this; _this = this;
stream = this.get('stream'); stream = this.get('stream');
$.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',
@ -251,7 +251,7 @@ Discourse.User = Discourse.Model.extend({
url += "&filter=" + (this.get('streamFilter')); url += "&filter=" + (this.get('streamFilter'));
} }
return $.ajax({ return Discourse.ajax({
url: url, url: url,
dataType: 'json', dataType: 'json',
cache: 'false', cache: 'false',
@ -372,7 +372,7 @@ Discourse.User.reopenClass({
@param {String} email An email address to check @param {String} email An email address to check
**/ **/
checkUsername: function(username, email) { checkUsername: function(username, email) {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL('/users/check_username'), url: Discourse.getURL('/users/check_username'),
type: 'GET', type: 'GET',
data: { data: {
@ -438,7 +438,7 @@ Discourse.User.reopenClass({
// Check the preload store first // Check the preload store first
return PreloadStore.getAndRemove("user_" + username, function() { return PreloadStore.getAndRemove("user_" + username, function() {
return $.ajax({ url: Discourse.getURL("/users/") + username + '.json' }); return Discourse.ajax({ url: Discourse.getURL("/users/") + username + '.json' });
}).then(function (json) { }).then(function (json) {
// Create a user from the resulting JSON // Create a user from the resulting JSON
@ -475,7 +475,7 @@ Discourse.User.reopenClass({
@returns Result of ajax call @returns Result of ajax call
**/ **/
createAccount: function(name, email, password, username, passwordConfirm, challenge) { createAccount: function(name, email, password, username, passwordConfirm, challenge) {
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL("/users"), url: Discourse.getURL("/users"),
dataType: 'json', dataType: 'json',
data: { data: {

View File

@ -52,15 +52,17 @@ Discourse.HeaderView = Discourse.View.extend({
}, },
showNotifications: function() { showNotifications: function() {
var _this = this;
$.get(Discourse.getURL("/notifications")).then(function(result) { var headerView = this;
_this.set('notifications', result.map(function(n) { Discourse.ajax('/notifications').then(function(result) {
headerView.set('notifications', result.map(function(n) {
return Discourse.Notification.create(n); return Discourse.Notification.create(n);
})); }));
// We've seen all the notifications now // We've seen all the notifications now
_this.set('currentUser.unread_notifications', 0); headerView.set('currentUser.unread_notifications', 0);
_this.set('currentUser.unread_private_messages', 0); headerView.set('currentUser.unread_private_messages', 0);
return _this.showDropdown($('#user-notifications')); headerView.showDropdown($('#user-notifications'));
}); });
return false; return false;
}, },

View File

@ -242,7 +242,7 @@ Discourse.CreateAccountView = Discourse.ModalBodyView.extend({
fetchConfirmationValue: function() { fetchConfirmationValue: function() {
var _this = this; var _this = this;
return $.ajax({ return Discourse.ajax({
url: Discourse.getURL('/users/hp.json'), url: Discourse.getURL('/users/hp.json'),
success: function(json) { success: function(json) {
_this.set('accountPasswordConfirm', json.value); _this.set('accountPasswordConfirm', json.value);

View File

@ -16,9 +16,12 @@ Discourse.ForgotPasswordView = Discourse.ModalBodyView.extend({
}).property('accountEmailOrUsername'), }).property('accountEmailOrUsername'),
submit: function() { submit: function() {
$.post(Discourse.getURL("/session/forgot_password"), {
username: this.get('accountEmailOrUsername') Discourse.ajax(Discourse.getURL("/session/forgot_password"), {
data: { username: this.get('accountEmailOrUsername') },
type: 'POST'
}); });
// don't tell people what happened, this keeps it more secure (ensure same on server) // don't tell people what happened, this keeps it more secure (ensure same on server)
this.flash(Em.String.i18n('forgot_password.complete')); this.flash(Em.String.i18n('forgot_password.complete'));
return false; return false;

View File

@ -35,20 +35,21 @@ Discourse.HistoryView = Discourse.View.extend({
}.observes('versionRight'), }.observes('versionRight'),
didInsertElement: function() { didInsertElement: function() {
var _this = this;
this.set('loading', true); this.set('loading', true);
this.set('postLeft', null); this.set('postLeft', null);
this.set('postRight', null); this.set('postRight', null);
return this.get('originalPost').loadVersions(function(result) {
var historyView = this;
this.get('originalPost').loadVersions().then(function(result) {
result.each(function(item) { result.each(function(item) {
item.description = "v" + item.number + " - " + Date.create(item.created_at).relative() + " - " + item.description = "v" + item.number + " - " + Date.create(item.created_at).relative() + " - " +
Em.String.i18n("changed_by", { author: item.display_username }); Em.String.i18n("changed_by", { author: item.display_username });
}); });
_this.set('loading', false); historyView.set('loading', false);
_this.set('versionLeft', result.first()); historyView.set('versionLeft', result.first());
_this.set('versionRight', result.last()); historyView.set('versionRight', result.last());
return _this.set('versions', result); historyView.set('versions', result);
}); });
} }
}); });

View File

@ -43,61 +43,66 @@ Discourse.LoginView = Discourse.ModalBodyView.extend({
}).property('loginName', 'loginPassword', 'loggingIn'), }).property('loginName', 'loginPassword', 'loggingIn'),
login: function() { login: function() {
var _this = this;
this.set('loggingIn', true); this.set('loggingIn', true);
$.post(Discourse.getURL("/session"), {
login: this.get('loginName'), var loginView = this;
password: this.get('loginPassword') Discourse.ajax(Discourse.getURL("/session"), {
}).success(function(result) { data: { login: this.get('loginName'), password: this.get('loginPassword') },
type: 'POST'
}).then(function (result) {
// Successful login
if (result.error) { if (result.error) {
_this.set('loggingIn', false); loginView.set('loggingIn', false);
if( result.reason === 'not_activated' ) { if( result.reason === 'not_activated' ) {
return _this.showView(Discourse.NotActivatedView.create({username: _this.get('loginName'), sentTo: result.sent_to_email, currentEmail: result.current_email})); return loginView.showView(Discourse.NotActivatedView.create({
username: loginView.get('loginName'),
sentTo: result.sent_to_email,
currentEmail: result.current_email
}));
} }
_this.flash(result.error, 'error'); loginView.flash(result.error, 'error');
} else { } else {
// Trigger the browser's password manager using the hidden static login form: // Trigger the browser's password manager using the hidden static login form:
var $hidden_login_form = $('#hidden-login-form'); var $hidden_login_form = $('#hidden-login-form');
$hidden_login_form.find('input[name=username]').val(_this.get('loginName')); $hidden_login_form.find('input[name=username]').val(loginView.get('loginName'));
$hidden_login_form.find('input[name=password]').val(_this.get('loginPassword')); $hidden_login_form.find('input[name=password]').val(loginView.get('loginPassword'));
$hidden_login_form.find('input[name=redirect]').val(window.location.href); $hidden_login_form.find('input[name=redirect]').val(window.location.href);
$hidden_login_form.find('input[name=authenticity_token]').val($('meta[name=csrf-token]').attr('content')); $hidden_login_form.find('input[name=authenticity_token]').val($('meta[name=csrf-token]').attr('content'));
$hidden_login_form.submit(); $hidden_login_form.submit();
} }
}).fail(function(result) {
_this.flash(Em.String.i18n('login.error'), 'error'); }, function(result) {
return _this.set('loggingIn', false); // Failed to login
}); loginView.flash(Em.String.i18n('login.error'), 'error');
loginView.set('loggingIn', false);
})
return false; return false;
}, },
authMessage: (function() { authMessage: (function() {
if (this.blank('authenticate')) { if (this.blank('authenticate')) return "";
return "";
}
return Em.String.i18n("login." + (this.get('authenticate')) + ".message"); return Em.String.i18n("login." + (this.get('authenticate')) + ".message");
}).property('authenticate'), }).property('authenticate'),
twitterLogin: function() { twitterLogin: function() {
var left, top;
this.set('authenticate', 'twitter'); this.set('authenticate', 'twitter');
left = this.get('lastX') - 400; var left = this.get('lastX') - 400;
top = this.get('lastY') - 200; var top = this.get('lastY') - 200;
return window.open(Discourse.getURL("/auth/twitter"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); return window.open(Discourse.getURL("/auth/twitter"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
}, },
facebookLogin: function() { facebookLogin: function() {
var left, top;
this.set('authenticate', 'facebook'); this.set('authenticate', 'facebook');
left = this.get('lastX') - 400; var left = this.get('lastX') - 400;
top = this.get('lastY') - 200; var top = this.get('lastY') - 200;
return window.open(Discourse.getURL("/auth/facebook"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); return window.open(Discourse.getURL("/auth/facebook"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
}, },
openidLogin: function(provider) { openidLogin: function(provider) {
var left, top; var left = this.get('lastX') - 400;
left = this.get('lastX') - 400; var top = this.get('lastY') - 200;
top = this.get('lastY') - 200;
if (provider === "yahoo") { if (provider === "yahoo") {
this.set("authenticate", 'yahoo'); this.set("authenticate", 'yahoo');
return window.open(Discourse.getURL("/auth/yahoo"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); return window.open(Discourse.getURL("/auth/yahoo"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
@ -108,15 +113,14 @@ Discourse.LoginView = Discourse.ModalBodyView.extend({
}, },
githubLogin: function() { githubLogin: function() {
var left, top;
this.set('authenticate', 'github'); this.set('authenticate', 'github');
left = this.get('lastX') - 400; var left = this.get('lastX') - 400;
top = this.get('lastY') - 200; var top = this.get('lastY') - 200;
return window.open(Discourse.getURL("/auth/github"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); return window.open(Discourse.getURL("/auth/github"), "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top);
}, },
personaLogin: function() { personaLogin: function() {
navigator.id.request(); navigator.id.request();
}, },
authenticationComplete: function(options) { authenticationComplete: function(options) {
@ -154,11 +158,11 @@ Discourse.LoginView = Discourse.ModalBodyView.extend({
this.set('loginName', $('#hidden-login-form input[name=username]').val()); this.set('loginName', $('#hidden-login-form input[name=username]').val());
this.set('loginPassword', $('#hidden-login-form input[name=password]').val()); this.set('loginPassword', $('#hidden-login-form input[name=password]').val());
var _this = this; var loginView = this;
return Em.run.next(function() { Em.run.next(function() {
return $('#login-account-password').keydown(function(e) { $('#login-account-password').keydown(function(e) {
if (e.keyCode === 13) { if (e.keyCode === 13) {
return _this.login(); loginView.login();
} }
}); });
}); });

View File

@ -12,7 +12,7 @@ Discourse.NotActivatedView = Discourse.ModalBodyView.extend({
emailSent: false, emailSent: false,
sendActivationEmail: function() { sendActivationEmail: function() {
$.get(Discourse.getURL('/users/') + this.get('username') + '/send_activation_email'); Discourse.ajax(Discourse.getURL('/users/') + this.get('username') + '/send_activation_email');
this.set('emailSent', true); this.set('emailSent', true);
} }
}); });

View File

@ -155,7 +155,7 @@ Discourse.PostView = Discourse.View.extend({
if ($aside.data('topic')) { if ($aside.data('topic')) {
topic_id = $aside.data('topic'); topic_id = $aside.data('topic');
} }
$.getJSON(Discourse.getURL("/posts/by_number/") + topic_id + "/" + ($aside.data('post')), function(result) { Discourse.ajax(Discourse.getURL("/posts/by_number/") + topic_id + "/" + ($aside.data('post'))).then(function (result) {
var parsed = $(result.cooked); var parsed = $(result.cooked);
parsed.replaceText(originalText, "<span class='highlighted'>" + originalText + "</span>"); parsed.replaceText(originalText, "<span class='highlighted'>" + originalText + "</span>");
$blockQuote.showHtml(parsed); $blockQuote.showHtml(parsed);

View File

@ -95,7 +95,7 @@ Discourse.SearchView = Discourse.View.extend({
this.currentSearch = null; this.currentSearch = null;
} }
this.searcher = this.searcher || Discourse.debounce(function(term, typeFilter) { this.searcher = this.searcher || Discourse.debounce(function(term, typeFilter) {
_this.currentSearch = $.ajax({ _this.currentSearch = Discourse.ajax({
url: Discourse.getURL('/search'), url: Discourse.getURL('/search'),
data: { data: {
term: term, term: term,

View File

@ -6,7 +6,7 @@
onlogin: function(assertion) { onlogin: function(assertion) {
if (readyCalled) { if (readyCalled) {
$.ajax({ Discourse.ajax({
type: 'POST', type: 'POST',
url: Discourse.getURL('/auth/persona/callback'), url: Discourse.getURL('/auth/persona/callback'),
data: { 'assertion': assertion }, data: { 'assertion': assertion },

View File

@ -5,20 +5,20 @@ describe("Discourse.Onebox", function() {
var anchor; var anchor;
beforeEach(function() { beforeEach(function() {
spyOn(jQuery, 'ajax').andCallThrough(); spyOn(Discourse, 'ajax').andCallThrough();
anchor = $("<a href='http://bla.com'></a>")[0]; anchor = $("<a href='http://bla.com'></a>")[0];
}); });
it("Stops rapid calls with cache true", function() { it("Stops rapid calls with cache true", function() {
Discourse.Onebox.load(anchor, true); Discourse.Onebox.load(anchor, true);
Discourse.Onebox.load(anchor, true); Discourse.Onebox.load(anchor, true);
expect($.ajax.calls.length).toBe(1); expect(Discourse.ajax.calls.length).toBe(1);
}); });
it("Stops rapid calls with cache false", function() { it("Stops rapid calls with cache false", function() {
Discourse.Onebox.load(anchor, false); Discourse.Onebox.load(anchor, false);
Discourse.Onebox.load(anchor, false); Discourse.Onebox.load(anchor, false);
expect($.ajax.calls.length).toBe(1); expect(Discourse.ajax.calls.length).toBe(1);
}); });
}); });