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() {
var _this = this;
_this.set('sentTestEmail', false);
$.ajax({
Discourse.ajax({
url: Discourse.getURL("/admin/email_logs/test"),
type: 'POST',
data: { email_address: this.get('testEmailAddress') },

View File

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

View File

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

View File

@ -18,7 +18,7 @@ Discourse.AdminUser = Discourse.Model.extend({
deleteAllPosts: function() {
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
@ -26,14 +26,14 @@ Discourse.AdminUser = Discourse.Model.extend({
this.set('admin', false);
this.set('can_grant_admin', true);
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() {
this.set('admin', true);
this.set('can_grant_admin', false);
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
@ -41,18 +41,18 @@ Discourse.AdminUser = Discourse.Model.extend({
this.set('moderator', false);
this.set('can_grant_moderation', true);
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() {
this.set('moderator', true);
this.set('can_grant_moderation', false);
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() {
$.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!");
},
@ -60,7 +60,7 @@ Discourse.AdminUser = Discourse.Model.extend({
this.set('can_approve', false);
this.set('approved', true);
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() {
@ -90,7 +90,7 @@ Discourse.AdminUser = Discourse.Model.extend({
_this = this;
if (duration = parseInt(window.prompt(Em.String.i18n('admin.user.ban_duration')), 10)) {
if (duration > 0) {
return $.ajax(Discourse.getURL("/admin/users/") + this.id + "/ban", {
return Discourse.ajax(Discourse.getURL("/admin/users/") + this.id + "/ban", {
type: 'PUT',
data: {duration: duration},
success: function() {
@ -107,7 +107,7 @@ Discourse.AdminUser = Discourse.Model.extend({
unban: function() {
var _this = this;
return $.ajax(Discourse.getURL("/admin/users/") + this.id + "/unban", {
return Discourse.ajax(Discourse.getURL("/admin/users/") + this.id + "/unban", {
type: 'PUT',
success: function() {
window.location.reload();
@ -121,7 +121,7 @@ Discourse.AdminUser = Discourse.Model.extend({
impersonate: function() {
var _this = this;
return $.ajax(Discourse.getURL("/admin/impersonate"), {
return Discourse.ajax(Discourse.getURL("/admin/impersonate"), {
type: 'POST',
data: {
username_or_email: this.get('username')
@ -150,7 +150,7 @@ Discourse.AdminUser.reopenClass({
user.set('can_approve', 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',
data: {
users: users.map(function(u) {
@ -161,7 +161,7 @@ Discourse.AdminUser.reopenClass({
},
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);
})
},
@ -169,7 +169,7 @@ Discourse.AdminUser.reopenClass({
findAll: function(query, filter) {
var result;
result = Em.A();
$.ajax({
Discourse.ajax({
url: Discourse.getURL("/admin/users/list/") + query + ".json",
data: {
filter: filter

View File

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

View File

@ -47,14 +47,14 @@ Discourse.FlaggedPost = Discourse.Post.extend({
deletePost: function() {
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 {
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() {
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() {
@ -67,7 +67,7 @@ Discourse.FlaggedPost.reopenClass({
findAll: function(filter) {
var result;
result = Em.A();
$.ajax({
Discourse.ajax({
url: Discourse.getURL("/admin/flags/") + filter + ".json",
success: function(data) {
var userLookup;

View File

@ -28,7 +28,7 @@ Discourse.GithubCommit.reopenClass({
findAll: function() {
var result;
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',
type: 'get',
data: { per_page: 25 },

View File

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

View File

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

View File

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

View File

@ -26,7 +26,7 @@ Discourse.VersionCheck = Discourse.Model.extend({
Discourse.VersionCheck.reopenClass({
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);
});
}

View File

@ -166,7 +166,7 @@ Discourse = Ember.Application.createWithMixins({
**/
logout: function() {
Discourse.KeyValueStore.abandonLocal();
return $.ajax(Discourse.getURL("/session/") + this.get('currentUser.username'), {
return Discourse.ajax(Discourse.getURL("/session/") + this.get('currentUser.username'), {
type: 'DELETE',
success: function(result) {
// 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);
},
/**
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() {
Discourse.bindDOMEvents();
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 (e.metaKey || e.ctrlKey || e.which === 2) {
$.get(Discourse.getURL("/clicks/track"), {
url: href,
post_id: postId,
topic_id: topicId,
redirect: false
Discourse.ajax(Discourse.getURL("/clicks/track"), {
data: {
url: href,
post_id: postId,
topic_id: topicId,
redirect: false
}
});
window.open(href, '_blank');
return false;
@ -82,11 +85,13 @@ Discourse.ClickTrack = {
// If we're on the same site, use the router and track via AJAX
if (href.indexOf(window.location.origin) === 0) {
$.get(Discourse.getURL("/clicks/track"), {
url: href,
post_id: postId,
topic_id: topicId,
redirect: false
Discourse.ajax(Discourse.getURL("/clicks/track"), {
data: {
url: href,
post_id: postId,
topic_id: topicId,
redirect: false
}
});
Discourse.URL.routeTo(href);
return false;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@ Discourse.InviteList = Discourse.Model.extend({
Discourse.InviteList.reopenClass({
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;
if (invitedList.pending) {
invitedList.pending = invitedList.pending.map(function(i) {

View File

@ -21,7 +21,7 @@ Discourse.Model = Ember.Object.extend(Discourse.Presence, {
args.error = function(xhr) {
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);
}
});
}
}
});
Discourse.Model.reopenClass({
/**
/**
$.get shortcut that uses Discourse.Url and returns a promise
**/
getAjax: function(url) {
var _this = this;
var promise = new Ember.Deferred();
$.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;
getModelAjax: function(url) {
var modelClass = this;
return Discourse.ajax({ url: url, cache: false, dataType: 'json' }).then(function (result) {
return modelClass.create(result);
});
},
@ -89,15 +73,10 @@ Discourse.Model.reopenClass({
@param {Object} klass Optional The class to instantiate
**/
extractByKey: function(collection, klass) {
var retval;
retval = {};
if (!collection) {
return retval;
}
var retval = {};
if (!collection) return retval;
collection.each(function(c) {
var obj;
obj = klass.create(c);
retval[c.id] = obj;
retval[c.id] = klass.create(c);
});
return retval;
}

View File

@ -68,7 +68,7 @@ Discourse.Post = Discourse.Model.extend({
bookmarkedChanged: (function() {
var _this = this;
return $.ajax({
return Discourse.ajax({
url: Discourse.getURL("/posts/") + (this.get('id')) + "/bookmark",
type: 'PUT',
data: {
@ -127,7 +127,7 @@ Discourse.Post = Discourse.Model.extend({
var data, metaData;
if (!this.get('newPost')) {
// We're updating a post
return $.ajax({
return Discourse.ajax({
url: Discourse.getURL("/posts/") + (this.get('id')),
type: 'PUT',
data: {
@ -157,7 +157,7 @@ Discourse.Post = Discourse.Model.extend({
data.meta_data = {};
Ember.keys(metaData).forEach(function(key) { data.meta_data[key] = metaData.get(key); });
}
return $.ajax({
return Discourse.ajax({
type: 'POST',
url: Discourse.getURL("/posts"),
data: data,
@ -172,11 +172,11 @@ Discourse.Post = Discourse.Model.extend({
},
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) {
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
@ -216,7 +216,7 @@ Discourse.Post = Discourse.Model.extend({
this.set('replies', []);
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');
loaded.each(function(reply) {
var post = Discourse.Post.create(reply);
@ -227,10 +227,8 @@ Discourse.Post = Discourse.Model.extend({
});
},
loadVersions: function(callback) {
return $.get(Discourse.getURL("/posts/") + (this.get('id')) + "/versions.json", function(result) {
return callback(result);
});
loadVersions: function() {
return Discourse.ajax(Discourse.getURL("/posts/") + (this.get('id')) + "/versions.json");
},
// Whether to show replies directly below
@ -284,7 +282,7 @@ Discourse.Post.reopenClass({
},
deleteMany: function(posts) {
return $.ajax(Discourse.getURL("/posts/destroy_many"), {
return Discourse.ajax(Discourse.getURL("/posts/destroy_many"), {
type: 'DELETE',
data: {
post_ids: posts.map(function(p) { return p.get('id'); })
@ -293,26 +291,26 @@ Discourse.Post.reopenClass({
},
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);
});
},
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);
});
},
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);
return Discourse.BBCode.buildQuoteBBCode(post, post.get('raw'));
});
},
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);
});
}

View File

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

View File

@ -14,7 +14,7 @@ Discourse.TopicList = Discourse.Model.extend({
if (moreUrl = this.get('more_topics_url')) {
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;
if (result) {
// the new topics loaded from the server
@ -106,7 +106,9 @@ Discourse.TopicList.reopenClass({
Discourse.set('transient.topicsList', 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('can_create_topic', result.topic_list.can_create_topic);
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
**/
changeUsername: function(newUsername) {
return $.ajax({
return Discourse.ajax({
url: Discourse.getURL("/users/") + (this.get('username_lower')) + "/preferences/username",
type: 'PUT',
data: {
@ -103,7 +103,7 @@ Discourse.User = Discourse.Model.extend({
@returns Result of ajax call
**/
changeEmail: function(email) {
return $.ajax({
return Discourse.ajax({
url: Discourse.getURL("/users/") + (this.get('username_lower')) + "/preferences/email",
type: 'PUT',
data: {
@ -131,7 +131,7 @@ Discourse.User = Discourse.Model.extend({
**/
save: function(finished) {
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',
'bio_raw',
'website',
@ -163,7 +163,7 @@ Discourse.User = Discourse.Model.extend({
changePassword: function(callback) {
var good;
good = false;
$.ajax({
Discourse.ajax({
url: Discourse.getURL("/session/forgot_password"),
dataType: 'json',
data: {
@ -209,7 +209,7 @@ Discourse.User = Discourse.Model.extend({
var stream,
_this = this;
stream = this.get('stream');
$.ajax({
Discourse.ajax({
url: Discourse.getURL("/user_actions/") + id + ".json",
dataType: 'json',
cache: 'false',
@ -251,7 +251,7 @@ Discourse.User = Discourse.Model.extend({
url += "&filter=" + (this.get('streamFilter'));
}
return $.ajax({
return Discourse.ajax({
url: url,
dataType: 'json',
cache: 'false',
@ -372,7 +372,7 @@ Discourse.User.reopenClass({
@param {String} email An email address to check
**/
checkUsername: function(username, email) {
return $.ajax({
return Discourse.ajax({
url: Discourse.getURL('/users/check_username'),
type: 'GET',
data: {
@ -438,7 +438,7 @@ Discourse.User.reopenClass({
// Check the preload store first
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) {
// Create a user from the resulting JSON
@ -475,7 +475,7 @@ Discourse.User.reopenClass({
@returns Result of ajax call
**/
createAccount: function(name, email, password, username, passwordConfirm, challenge) {
return $.ajax({
return Discourse.ajax({
url: Discourse.getURL("/users"),
dataType: 'json',
data: {

View File

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

View File

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

View File

@ -16,9 +16,12 @@ Discourse.ForgotPasswordView = Discourse.ModalBodyView.extend({
}).property('accountEmailOrUsername'),
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)
this.flash(Em.String.i18n('forgot_password.complete'));
return false;

View File

@ -35,20 +35,21 @@ Discourse.HistoryView = Discourse.View.extend({
}.observes('versionRight'),
didInsertElement: function() {
var _this = this;
this.set('loading', true);
this.set('postLeft', 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) {
item.description = "v" + item.number + " - " + Date.create(item.created_at).relative() + " - " +
Em.String.i18n("changed_by", { author: item.display_username });
});
_this.set('loading', false);
_this.set('versionLeft', result.first());
_this.set('versionRight', result.last());
return _this.set('versions', result);
historyView.set('loading', false);
historyView.set('versionLeft', result.first());
historyView.set('versionRight', result.last());
historyView.set('versions', result);
});
}
});

View File

@ -43,61 +43,66 @@ Discourse.LoginView = Discourse.ModalBodyView.extend({
}).property('loginName', 'loginPassword', 'loggingIn'),
login: function() {
var _this = this;
this.set('loggingIn', true);
$.post(Discourse.getURL("/session"), {
login: this.get('loginName'),
password: this.get('loginPassword')
}).success(function(result) {
var loginView = this;
Discourse.ajax(Discourse.getURL("/session"), {
data: { login: this.get('loginName'), password: this.get('loginPassword') },
type: 'POST'
}).then(function (result) {
// Successful login
if (result.error) {
_this.set('loggingIn', false);
loginView.set('loggingIn', false);
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 {
// Trigger the browser's password manager using the hidden static 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=password]').val(_this.get('loginPassword'));
$hidden_login_form.find('input[name=username]').val(loginView.get('loginName'));
$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=authenticity_token]').val($('meta[name=csrf-token]').attr('content'));
$hidden_login_form.submit();
}
}).fail(function(result) {
_this.flash(Em.String.i18n('login.error'), 'error');
return _this.set('loggingIn', false);
});
}, function(result) {
// Failed to login
loginView.flash(Em.String.i18n('login.error'), 'error');
loginView.set('loggingIn', false);
})
return false;
},
authMessage: (function() {
if (this.blank('authenticate')) {
return "";
}
if (this.blank('authenticate')) return "";
return Em.String.i18n("login." + (this.get('authenticate')) + ".message");
}).property('authenticate'),
twitterLogin: function() {
var left, top;
this.set('authenticate', 'twitter');
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
var left = this.get('lastX') - 400;
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);
},
facebookLogin: function() {
var left, top;
this.set('authenticate', 'facebook');
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
var left = this.get('lastX') - 400;
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);
},
openidLogin: function(provider) {
var left, top;
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
var left = this.get('lastX') - 400;
var top = this.get('lastY') - 200;
if (provider === "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);
@ -108,15 +113,14 @@ Discourse.LoginView = Discourse.ModalBodyView.extend({
},
githubLogin: function() {
var left, top;
this.set('authenticate', 'github');
left = this.get('lastX') - 400;
top = this.get('lastY') - 200;
var left = this.get('lastX') - 400;
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);
},
personaLogin: function() {
navigator.id.request();
navigator.id.request();
},
authenticationComplete: function(options) {
@ -154,11 +158,11 @@ Discourse.LoginView = Discourse.ModalBodyView.extend({
this.set('loginName', $('#hidden-login-form input[name=username]').val());
this.set('loginPassword', $('#hidden-login-form input[name=password]').val());
var _this = this;
return Em.run.next(function() {
return $('#login-account-password').keydown(function(e) {
var loginView = this;
Em.run.next(function() {
$('#login-account-password').keydown(function(e) {
if (e.keyCode === 13) {
return _this.login();
loginView.login();
}
});
});

View File

@ -12,7 +12,7 @@ Discourse.NotActivatedView = Discourse.ModalBodyView.extend({
emailSent: false,
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);
}
});

View File

@ -155,7 +155,7 @@ Discourse.PostView = Discourse.View.extend({
if ($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);
parsed.replaceText(originalText, "<span class='highlighted'>" + originalText + "</span>");
$blockQuote.showHtml(parsed);

View File

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

View File

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

View File

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