must go first:
text = text.replace(/([\W_]|^)(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\2([\W_]|$)/g,
- "$1$3$4");
+ '$1$3$4');
text = text.replace(/([\W_]|^)(\*|_)(?=\S)([^\r\*_]*?\S)\2([\W_]|$)/g,
- "$1$3$4");
+ '$1$3$4');
return text;
}
- function _DoBlockQuotes(text) {
-
+ function _DoBlockQuotes(text) {
/*
text = text.replace(/
( // Wrap whole match in $1
@@ -1075,33 +1069,33 @@ else
*/
text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,
- function (wholeMatch, m1) {
+ function(wholeMatch, m1) {
var bq = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
- bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0"); // trim one level of quoting
+ bq = bq.replace(/^[ \t]*>[ \t]?/gm, '~0'); // trim one level of quoting
// attacklab: clean up hack
- bq = bq.replace(/~0/g, "");
+ bq = bq.replace(/~0/g, '');
- bq = bq.replace(/^[ \t]+$/gm, ""); // trim whitespace-only lines
+ bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
bq = _RunBlockGamut(bq); // recurse
- bq = bq.replace(/(^|\n)/g, "$1 ");
+ bq = bq.replace(/(^|\n)/g, '$1 ');
// These leading spaces screw with content, so we need to fix that:
bq = bq.replace(
/(\s*[^\r]+?<\/pre>)/gm,
- function (wholeMatch, m1) {
+ function(wholeMatch, m1) {
var pre = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
- pre = pre.replace(/^ /mg, "~0");
- pre = pre.replace(/~0/g, "");
+ pre = pre.replace(/^ /mg, '~0');
+ pre = pre.replace(/~0/g, '');
return pre;
});
- return hashBlock("\n" + bq + "\n
");
+ return hashBlock('\n' + bq + '\n
');
}
);
return text;
@@ -1114,12 +1108,12 @@ else
//
// Strip leading and trailing lines:
- text = text.replace(/^\n+/g, "");
- text = text.replace(/\n+$/g, "");
+ text = text.replace(/^\n+/g, '');
+ text = text.replace(/\n+$/g, '');
var grafs = text.split(/\n{2,}/g);
var grafsOut = [];
-
+
var markerRe = /~K(\d+)K/;
//
@@ -1135,11 +1129,10 @@ else
}
else if (/\S/.test(str)) {
str = _RunSpanGamut(str);
- str = str.replace(/^([ \t]*)/g, "");
- str += "
"
+ str = str.replace(/^([ \t]*)/g, '');
+ str += '
';
grafsOut.push(str);
- }
-
+ }
}
//
// Unhashify HTML blocks
@@ -1150,14 +1143,14 @@ else
var foundAny = true;
while (foundAny) { // we may need several runs, since the data may be nested
foundAny = false;
- grafsOut[i] = grafsOut[i].replace(/~K(\d+)K/g, function (wholeMatch, id) {
+ grafsOut[i] = grafsOut[i].replace(/~K(\d+)K/g, function(wholeMatch, id) {
foundAny = true;
return g_html_blocks[id];
});
}
}
}
- return grafsOut.join("\n\n");
+ return grafsOut.join('\n\n');
}
function _EncodeAmpsAndAngles(text) {
@@ -1165,10 +1158,10 @@ else
// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
// http://bumppo.net/projects/amputator/
- text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, "&");
+ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&');
// Encode naked <'s
- text = text.replace(/<(?![a-z\/?\$!])/gi, "<");
+ text = text.replace(/<(?![a-z\/?\$!])/gi, '<');
return text;
}
@@ -1194,18 +1187,17 @@ else
return text;
}
- function _DoAutoLinks(text) {
-
+ function _DoAutoLinks(text) {
// note that at this point, all other URL in the text are already hyperlinked as
// *except* for the case
// automatically add < and > around unadorned raw hyperlinks
// must be preceded by space/BOF and followed by non-word/EOF character
- text = text.replace(/(^|\s)(https?|ftp)(:\/\/[-A-Z0-9+&@#\/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#\/%=~_|\[\]])($|\W)/gi, "$1<$2$3>$4");
+ text = text.replace(/(^|\s)(https?|ftp)(:\/\/[-A-Z0-9+&@#\/%?=~_|\[\]\(\)!:,\.;]*[-A-Z0-9+&@#\/%=~_|\[\]])($|\W)/gi, '$1<$2$3>$4');
// autolink anything like
-
- var replacer = function (wholematch, m1) { return "" + pluginHooks.plainLinkText(m1) + ""; }
+
+ var replacer = function(wholematch, m1) { return '' + pluginHooks.plainLinkText(m1) + ''; };
text = text.replace(/<((https?|ftp):[^'">\s]+)>/gi, replacer);
// Email addresses:
@@ -1237,7 +1229,7 @@ else
// Swap back in all the special characters we've hidden.
//
text = text.replace(/~E(\d+)E/g,
- function (wholeMatch, m1) {
+ function(wholeMatch, m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
}
@@ -1253,10 +1245,10 @@ else
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
- text = text.replace(/^(\t|[ ]{1,4})/gm, "~0"); // attacklab: g_tab_width
+ text = text.replace(/^(\t|[ ]{1,4})/gm, '~0'); // attacklab: g_tab_width
// attacklab: clean up hack
- text = text.replace(/~0/g, "")
+ text = text.replace(/~0/g, '');
return text;
}
@@ -1265,12 +1257,12 @@ else
if (!/\t/.test(text))
return text;
- var spaces = [" ", " ", " ", " "],
- skew = 0,
- v;
+ var spaces = [' ', ' ', ' ', ' '],
+ skew = 0,
+ v;
- return text.replace(/[\n\t]/g, function (match, offset) {
- if (match === "\n") {
+ return text.replace(/[\n\t]/g, function(match, offset) {
+ if (match === '\n') {
skew = offset + 1;
return match;
}
@@ -1287,20 +1279,20 @@ else
// Replacing encodeProblemUrlChars with attributeSafeUrl. See more at https://code.google.com/p/pagedown/source/detail?r=016a78c093843e203de5364117d34d406a09e8c0
function attributeSafeUrl(url) {
url = attributeEncode(url);
- url = escapeCharacters(url, "*_:()[]")
+ url = escapeCharacters(url, '*_:()[]');
return url;
}
function escapeCharacters(text, charsToEscape, afterBackslash) {
// First we have to escape the escape characters so that
// we can build a character class out of them
- var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g, "\\$1") + "])";
+ var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
if (afterBackslash) {
- regexString = "\\\\" + regexString;
+ regexString = '\\\\' + regexString;
}
- var regex = new RegExp(regexString, "g");
+ var regex = new RegExp(regexString, 'g');
text = text.replace(regex, escapeCharacters_callback);
return text;
@@ -1309,9 +1301,7 @@ else
function escapeCharacters_callback(wholeMatch, m1) {
var charCodeToEscape = m1.charCodeAt(0);
- return "~E" + charCodeToEscape + "E";
- }
-
- }; // end of the Markdown.Converter constructor
-
+ return '~E' + charCodeToEscape + 'E';
+ }
+ }; // end of the Markdown.Converter constructor
})();
diff --git a/lms/static/js/Markdown.Editor.js b/lms/static/js/Markdown.Editor.js
index 491d0f30ff..95e45a4464 100644
--- a/lms/static/js/Markdown.Editor.js
+++ b/lms/static/js/Markdown.Editor.js
@@ -1,14 +1,13 @@
// needs Markdown.Converter.js at the moment
-(function () {
-
+(function() {
var util = {},
position = {},
ui = {},
doc = window.document,
re = window.RegExp,
nav = window.navigator,
- SETTINGS = { lineLength: 72 },
+ SETTINGS = {lineLength: 72},
// Used to work around some browser bugs where we can't use feature testing.
uaSniffed = {
@@ -26,30 +25,30 @@
// -------------------------------------------------------------------
// The text that appears on the dialog box when entering links.
- var linkDialogText = gettext("Insert Hyperlink"),
+ var linkDialogText = gettext('Insert Hyperlink'),
linkUrlHelpText = gettext("e.g. 'http://google.com/'"),
- linkDestinationLabel = gettext("Link Description"),
+ linkDestinationLabel = gettext('Link Description'),
linkDestinationHelpText = gettext("e.g. 'google'"),
- linkDestinationError = gettext("Please provide a description of the link destination."),
- linkDefaultText = "http://"; // The default text that appears in input
+ linkDestinationError = gettext('Please provide a description of the link destination.'),
+ linkDefaultText = 'http://'; // The default text that appears in input
// The text that appears on the dialog box when entering Images.
- var imageDialogText = gettext("Insert Image (upload file or type URL)"),
+ var imageDialogText = gettext('Insert Image (upload file or type URL)'),
imageUrlHelpText = gettext("Type in a URL or use the \"Choose File\" button to upload a file from your machine. (e.g. 'http://example.com/img/clouds.jpg')"), // eslint-disable-line max-len
- imageDescriptionLabel = gettext("Image Description"),
- imageDefaultText = "http://", // The default text that appears in input
+ imageDescriptionLabel = gettext('Image Description'),
+ imageDefaultText = 'http://', // The default text that appears in input
imageDescError = gettext('Please describe this image or agree that it has no contextual value by checking the checkbox.'), // eslint-disable-line max-len
imageDescriptionHelpText = gettext("e.g. 'Sky with clouds'. The description is helpful for users who cannot see the image."), // eslint-disable-line max-len
imageDescriptionHelpLink = {
href: 'http://www.w3.org/TR/html5/embedded-content-0.html#alt',
- text: gettext("How to create useful text alternatives.")
+ text: gettext('How to create useful text alternatives.')
},
imageIsDecorativeLabel = gettext('This image is for decorative purposes only and does not require a description.'); // eslint-disable-line max-len
// Text that is shared between both link and image dialog boxes.
- var defaultHelpHoverTitle = gettext("Markdown Editing Help"),
- urlLabel = gettext("URL"),
- urlError = gettext("Please provide a valid URL.");
+ var defaultHelpHoverTitle = gettext('Markdown Editing Help'),
+ urlLabel = gettext('URL'),
+ urlError = gettext('Please provide a valid URL.');
// -------------------------------------------------------------------
// END OF YOUR CHANGES
@@ -63,55 +62,53 @@
// - getConverter() returns the markdown converter object that was passed to the constructor
// - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op.
// - refreshPreview() forces the preview to be updated. This method is only available after run() was called.
- Markdown.Editor = function (markdownConverter, idPostfix, help, imageUploadHandler) {
-
- idPostfix = idPostfix || "";
+ Markdown.Editor = function(markdownConverter, idPostfix, help, imageUploadHandler) {
+ idPostfix = idPostfix || '';
var hooks = this.hooks = new Markdown.HookCollection();
- hooks.addNoop("onPreviewPush"); // called with no arguments after the preview has been refreshed
- hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
- hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates
+ hooks.addNoop('onPreviewPush'); // called with no arguments after the preview has been refreshed
+ hooks.addNoop('postBlockquoteCreation'); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
+ hooks.addFalse('insertImageDialog'); /* called with one parameter: a callback to be called with the URL of the image. If the application creates
* its own image insertion dialog, this hook should return true, and the callback should be called with the chosen
* image url (or null if the user cancelled). If this hook returns false, the default dialog will be used.
*/
this.util = util;
- this.getConverter = function () { return markdownConverter; }
+ this.getConverter = function() { return markdownConverter; };
var that = this,
panels;
- this.run = function () {
+ this.run = function() {
if (panels)
return; // already initialized
panels = new PanelCollection(idPostfix);
var commandManager = new CommandManager(hooks);
- var previewManager = new PreviewManager(markdownConverter, panels, function (text, previewSet) { hooks.onPreviewPush(text, previewSet); });
+ var previewManager = new PreviewManager(markdownConverter, panels, function(text, previewSet) { hooks.onPreviewPush(text, previewSet); });
var undoManager, uiManager;
if (!/\?noundo/.test(doc.location.href)) {
- undoManager = new UndoManager(function () {
+ undoManager = new UndoManager(function() {
previewManager.refresh();
if (uiManager) // not available on the first call
uiManager.setUndoRedoButtonStates();
}, panels);
- this.textOperation = function (f) {
+ this.textOperation = function(f) {
undoManager.setCommandMode();
f();
that.refreshPreview();
- }
+ };
}
uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help, imageUploadHandler);
uiManager.setUndoRedoButtonStates();
- var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); };
+ var forceRefresh = that.refreshPreview = function() { previewManager.refresh(true); };
forceRefresh();
- };
-
- }
+ };
+ };
// before: contains all the text in the input box BEFORE the selection.
// after: contains all the text in the input box AFTER the selection.
@@ -119,46 +116,43 @@
// startRegex: a regular expression to find the start tag
// endRegex: a regular expresssion to find the end tag
- Chunks.prototype.findTags = function (startRegex, endRegex) {
-
+ Chunks.prototype.findTags = function(startRegex, endRegex) {
var chunkObj = this;
var regex;
- if (startRegex) {
-
- regex = util.extendRegExp(startRegex, "", "$");
+ if (startRegex) {
+ regex = util.extendRegExp(startRegex, '', '$');
this.before = this.before.replace(regex,
- function (match) {
+ function(match) {
chunkObj.startTag = chunkObj.startTag + match;
- return "";
+ return '';
});
- regex = util.extendRegExp(startRegex, "^", "");
+ regex = util.extendRegExp(startRegex, '^', '');
this.selection = this.selection.replace(regex,
- function (match) {
+ function(match) {
chunkObj.startTag = chunkObj.startTag + match;
- return "";
+ return '';
});
}
- if (endRegex) {
-
- regex = util.extendRegExp(endRegex, "", "$");
+ if (endRegex) {
+ regex = util.extendRegExp(endRegex, '', '$');
this.selection = this.selection.replace(regex,
- function (match) {
+ function(match) {
chunkObj.endTag = match + chunkObj.endTag;
- return "";
+ return '';
});
- regex = util.extendRegExp(endRegex, "^", "");
+ regex = util.extendRegExp(endRegex, '^', '');
this.after = this.after.replace(regex,
- function (match) {
+ function(match) {
chunkObj.endTag = match + chunkObj.endTag;
- return "";
+ return '';
});
}
};
@@ -167,21 +161,20 @@
// to the before/after regions.
//
// If remove is true, the whitespace disappears.
- Chunks.prototype.trimWhitespace = function (remove) {
+ Chunks.prototype.trimWhitespace = function(remove) {
var beforeReplacer, afterReplacer, that = this;
if (remove) {
- beforeReplacer = afterReplacer = "";
+ beforeReplacer = afterReplacer = '';
} else {
- beforeReplacer = function (s) { that.before += s; return ""; }
- afterReplacer = function (s) { that.after = s + that.after; return ""; }
+ beforeReplacer = function(s) { that.before += s; return ''; };
+ afterReplacer = function(s) { that.after = s + that.after; return ''; };
}
this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer);
};
- Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) {
-
+ Chunks.prototype.skipLines = function(nLinesBefore, nLinesAfter, findExtraNewlines) {
if (nLinesBefore === undefined) {
nLinesBefore = 1;
}
@@ -198,48 +191,46 @@
// chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985
if (navigator.userAgent.match(/Chrome/)) {
- "X".match(/()./);
+ 'X'.match(/()./);
}
- this.selection = this.selection.replace(/(^\n*)/, "");
+ this.selection = this.selection.replace(/(^\n*)/, '');
this.startTag = this.startTag + re.$1;
- this.selection = this.selection.replace(/(\n*$)/, "");
+ this.selection = this.selection.replace(/(\n*$)/, '');
this.endTag = this.endTag + re.$1;
- this.startTag = this.startTag.replace(/(^\n*)/, "");
+ this.startTag = this.startTag.replace(/(^\n*)/, '');
this.before = this.before + re.$1;
- this.endTag = this.endTag.replace(/(\n*$)/, "");
+ this.endTag = this.endTag.replace(/(\n*$)/, '');
this.after = this.after + re.$1;
- if (this.before) {
-
- regexText = replacementText = "";
+ if (this.before) {
+ regexText = replacementText = '';
while (nLinesBefore--) {
- regexText += "\\n?";
- replacementText += "\n";
+ regexText += '\\n?';
+ replacementText += '\n';
}
if (findExtraNewlines) {
- regexText = "\\n*";
+ regexText = '\\n*';
}
- this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
+ this.before = this.before.replace(new re(regexText + '$', ''), replacementText);
}
- if (this.after) {
-
- regexText = replacementText = "";
+ if (this.after) {
+ regexText = replacementText = '';
while (nLinesAfter--) {
- regexText += "\\n?";
- replacementText += "\n";
+ regexText += '\\n?';
+ replacementText += '\n';
}
if (findExtraNewlines) {
- regexText = "\\n*";
+ regexText = '\\n*';
}
- this.after = this.after.replace(new re(regexText, ""), replacementText);
+ this.after = this.after.replace(new re(regexText, ''), replacementText);
}
};
@@ -262,10 +253,10 @@
// and 8) and ONLY on button clicks. Keyboard shortcuts work
// normally since the focus never leaves the textarea.
function PanelCollection(postfix) {
- this.buttonBar = doc.getElementById("wmd-button-bar" + postfix);
- this.preview = doc.getElementById("wmd-preview" + postfix);
- this.input = doc.getElementById("wmd-input" + postfix);
- };
+ this.buttonBar = doc.getElementById('wmd-button-bar' + postfix);
+ this.preview = doc.getElementById('wmd-preview' + postfix);
+ this.input = doc.getElementById('wmd-input' + postfix);
+ }
util.isValidUrl = function(url) {
return /^((?:http|https|ftp):\/{2}|\/)[^]+$/.test(url);
@@ -273,25 +264,24 @@
// Returns true if the DOM element is visible, false if it's hidden.
// Checks if display is anything other than none.
- util.isVisible = function (elem) {
-
+ util.isVisible = function(elem) {
if (window.getComputedStyle) {
// Most browsers
- return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
+ return window.getComputedStyle(elem, null).getPropertyValue('display') !== 'none';
}
else if (elem.currentStyle) {
// IE
- return elem.currentStyle["display"] !== "none";
+ return elem.currentStyle['display'] !== 'none';
}
};
// Adds a listener callback to a DOM element which is fired on a specified
// event.
- util.addEvent = function (elem, event, listener) {
+ util.addEvent = function(elem, event, listener) {
if (elem.attachEvent) {
// IE only. The "on" is mandatory.
- elem.attachEvent("on" + event, listener);
+ elem.attachEvent('on' + event, listener);
}
else {
// Other browsers.
@@ -302,10 +292,10 @@
// Removes a listener callback from a DOM element which is fired on a specified
// event.
- util.removeEvent = function (elem, event, listener) {
+ util.removeEvent = function(elem, event, listener) {
if (elem.detachEvent) {
// IE only. The "on" is mandatory.
- elem.detachEvent("on" + event, listener);
+ elem.detachEvent('on' + event, listener);
}
else {
// Other browsers.
@@ -314,9 +304,9 @@
};
// Converts \r\n and \r to \n.
- util.fixEolChars = function (text) {
- text = text.replace(/\r\n/g, "\n");
- text = text.replace(/\r/g, "\n");
+ util.fixEolChars = function(text) {
+ text = text.replace(/\r\n/g, '\n');
+ text = text.replace(/\r/g, '\n');
return text;
};
@@ -328,35 +318,34 @@
// The flags are unchanged.
//
// regex is a RegExp, pre and post are strings.
- util.extendRegExp = function (regex, pre, post) {
-
+ util.extendRegExp = function(regex, pre, post) {
if (pre === null || pre === undefined) {
- pre = "";
+ pre = '';
}
if (post === null || post === undefined) {
- post = "";
+ post = '';
}
var pattern = regex.toString();
var flags;
// Replace the flags with empty space and store them.
- pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) {
+ pattern = pattern.replace(/\/([gim]*)$/, function(wholeMatch, flagsPart) {
flags = flagsPart;
- return "";
+ return '';
});
// Remove the slash delimiters on the regular expression.
- pattern = pattern.replace(/(^\/|\/$)/g, "");
+ pattern = pattern.replace(/(^\/|\/$)/g, '');
pattern = pre + pattern + post;
return new re(pattern, flags);
- }
+ };
// UNFINISHED
// The assignment in the while loop makes jslint cranky.
// I'll change it to a better loop later.
- position.getTop = function (elem, isInner) {
+ position.getTop = function(elem, isInner) {
var result = elem.offsetTop;
if (!isInner) {
while (elem = elem.offsetParent) {
@@ -366,16 +355,15 @@
return result;
};
- position.getHeight = function (elem) {
+ position.getHeight = function(elem) {
return elem.offsetHeight || elem.scrollHeight;
};
- position.getWidth = function (elem) {
+ position.getWidth = function(elem) {
return elem.offsetWidth || elem.scrollWidth;
};
- position.getPageSize = function () {
-
+ position.getPageSize = function() {
var scrollWidth, scrollHeight;
var innerWidth, innerHeight;
@@ -416,18 +404,17 @@
// Handles pushing and popping TextareaStates for undo/redo commands.
// I should rename the stack variables to list.
- function UndoManager(callback, panels) {
-
+ function UndoManager(callback, panels) {
var undoObj = this;
var undoStack = []; // A stack of undo states
var stackPtr = 0; // The index of the current state
- var mode = "none";
+ var mode = 'none';
var lastState; // The last state
var timer; // The setTimeout handle for cancelling the timer
var inputStateObj;
// Set the mode for later logic steps.
- var setMode = function (newMode, noSave) {
+ var setMode = function(newMode, noSave) {
if (mode != newMode) {
mode = newMode;
if (!noSave) {
@@ -435,7 +422,7 @@
}
}
- if (!uaSniffed.isIE || mode != "moving") {
+ if (!uaSniffed.isIE || mode != 'moving') {
timer = setTimeout(refreshState, 1);
}
else {
@@ -443,22 +430,22 @@
}
};
- var refreshState = function (isInitialState) {
+ var refreshState = function(isInitialState) {
inputStateObj = new TextareaState(panels, isInitialState);
timer = undefined;
};
- this.setCommandMode = function () {
- mode = "command";
+ this.setCommandMode = function() {
+ mode = 'command';
saveState();
timer = setTimeout(refreshState, 0);
};
- this.canUndo = function () {
+ this.canUndo = function() {
return stackPtr > 1;
};
- this.canRedo = function () {
+ this.canRedo = function() {
if (undoStack[stackPtr + 1]) {
return true;
}
@@ -466,8 +453,7 @@
};
// Removes the last state and restores it.
- this.undo = function () {
-
+ this.undo = function() {
if (undoObj.canUndo()) {
if (lastState) {
// What about setting state -1 to null or checking for undefined?
@@ -484,16 +470,14 @@
}
}
- mode = "none";
+ mode = 'none';
panels.input.focus();
refreshState();
};
// Redo an action.
- this.redo = function () {
-
- if (undoObj.canRedo()) {
-
+ this.redo = function() {
+ if (undoObj.canRedo()) {
undoStack[++stackPtr].restore();
if (callback) {
@@ -501,19 +485,19 @@
}
}
- mode = "none";
+ mode = 'none';
panels.input.focus();
refreshState();
};
// Push the input area state to the stack.
- var saveState = function () {
+ var saveState = function() {
var currState = inputStateObj || new TextareaState(panels);
if (!currState) {
return false;
}
- if (mode == "moving") {
+ if (mode == 'moving') {
if (!lastState) {
lastState = currState;
}
@@ -532,32 +516,30 @@
}
};
- var handleCtrlYZ = function (event) {
-
+ var handleCtrlYZ = function(event) {
var handled = false;
- if (event.ctrlKey || event.metaKey) {
-
+ if (event.ctrlKey || event.metaKey) {
// IE and Opera do not support charCode.
var keyCode = event.charCode || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
switch (keyCodeChar) {
- case "y":
- undoObj.redo();
- handled = true;
- break;
+ case 'y':
+ undoObj.redo();
+ handled = true;
+ break;
- case "z":
- if (!event.shiftKey) {
- undoObj.undo();
- }
- else {
- undoObj.redo();
- }
- handled = true;
- break;
+ case 'z':
+ if (!event.shiftKey) {
+ undoObj.undo();
+ }
+ else {
+ undoObj.redo();
+ }
+ handled = true;
+ break;
}
}
@@ -573,43 +555,41 @@
};
// Set the mode depending on what is going on in the input area.
- var handleModeChange = function (event) {
-
- if (!event.ctrlKey && !event.metaKey) {
-
+ var handleModeChange = function(event) {
+ if (!event.ctrlKey && !event.metaKey) {
var keyCode = event.keyCode;
if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
// 33 - 40: page up/dn and arrow keys
// 63232 - 63235: page up/dn and arrow keys on safari
- setMode("moving");
+ setMode('moving');
}
else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
// 8: backspace
// 46: delete
// 127: delete
- setMode("deleting");
+ setMode('deleting');
}
else if (keyCode == 13) {
// 13: Enter
- setMode("newlines");
+ setMode('newlines');
}
else if (keyCode == 27) {
// 27: escape
- setMode("escape");
+ setMode('escape');
}
else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
// 16-20 are shift, etc.
// 91: left window key
// I think this might be a little messed up since there are
// a lot of nonprinting keys above 20.
- setMode("typing");
+ setMode('typing');
}
}
};
- var setEventHandlers = function () {
- util.addEvent(panels.input, "keypress", function (event) {
+ var setEventHandlers = function() {
+ util.addEvent(panels.input, 'keypress', function(event) {
// keyCode 89: y
// keyCode 90: z
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
@@ -617,27 +597,27 @@
}
});
- var handlePaste = function () {
+ var handlePaste = function() {
if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) {
if (timer == undefined) {
- mode = "paste";
+ mode = 'paste';
saveState();
refreshState();
}
}
};
- util.addEvent(panels.input, "keydown", handleCtrlYZ);
- util.addEvent(panels.input, "keydown", handleModeChange);
- util.addEvent(panels.input, "mousedown", function () {
- setMode("moving");
+ util.addEvent(panels.input, 'keydown', handleCtrlYZ);
+ util.addEvent(panels.input, 'keydown', handleModeChange);
+ util.addEvent(panels.input, 'mousedown', function() {
+ setMode('moving');
});
panels.input.onpaste = handlePaste;
panels.input.ondrop = handlePaste;
};
- var init = function () {
+ var init = function() {
setEventHandlers();
refreshState(true);
saveState();
@@ -650,12 +630,11 @@
// The input textarea state/contents.
// This is used to implement undo/redo by the undo manager.
- function TextareaState(panels, isInitialState) {
-
+ function TextareaState(panels, isInitialState) {
// Aliases
var stateObj = this;
var inputArea = panels.input;
- this.init = function () {
+ this.init = function() {
if (!util.isVisible(inputArea)) {
return;
}
@@ -667,50 +646,43 @@
this.scrollTop = inputArea.scrollTop;
if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
this.text = inputArea.value;
- }
-
- }
+ }
+ };
// Sets the selected text in the input box after we've performed an
// operation.
- this.setInputAreaSelection = function () {
-
+ this.setInputAreaSelection = function() {
if (!util.isVisible(inputArea)) {
return;
}
- if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
-
+ if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
inputArea.focus();
inputArea.selectionStart = stateObj.start;
inputArea.selectionEnd = stateObj.end;
inputArea.scrollTop = stateObj.scrollTop;
}
- else if (doc.selection) {
-
+ else if (doc.selection) {
if (doc.activeElement && doc.activeElement !== inputArea) {
return;
}
inputArea.focus();
var range = inputArea.createTextRange();
- range.moveStart("character", -inputArea.value.length);
- range.moveEnd("character", -inputArea.value.length);
- range.moveEnd("character", stateObj.end);
- range.moveStart("character", stateObj.start);
+ range.moveStart('character', -inputArea.value.length);
+ range.moveEnd('character', -inputArea.value.length);
+ range.moveEnd('character', stateObj.end);
+ range.moveStart('character', stateObj.start);
range.select();
}
};
- this.setInputAreaSelectionStartEnd = function () {
-
- if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
-
+ this.setInputAreaSelectionStartEnd = function() {
+ if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
stateObj.start = inputArea.selectionStart;
stateObj.end = inputArea.selectionEnd;
}
- else if (doc.selection) {
-
+ else if (doc.selection) {
stateObj.text = util.fixEolChars(inputArea.value);
// IE loses the selection in the textarea when buttons are
@@ -719,12 +691,12 @@
var range = panels.ieCachedRange || doc.selection.createRange();
var fixedRange = util.fixEolChars(range.text);
- var marker = "\x07";
+ var marker = '\x07';
var markedRange = marker + fixedRange + marker;
range.text = markedRange;
var inputText = util.fixEolChars(inputArea.value);
- range.moveStart("character", -markedRange.length);
+ range.moveStart('character', -markedRange.length);
range.text = fixedRange;
stateObj.start = inputText.indexOf(marker);
@@ -733,9 +705,9 @@
var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
if (len) {
- range.moveStart("character", -fixedRange.length);
+ range.moveStart('character', -fixedRange.length);
while (len--) {
- fixedRange += "\n";
+ fixedRange += '\n';
stateObj.end += 1;
}
range.text = fixedRange;
@@ -751,8 +723,7 @@
};
// Restore this state into the input area.
- this.restore = function () {
-
+ this.restore = function() {
if (stateObj.text != undefined && stateObj.text != inputArea.value) {
inputArea.value = stateObj.text;
}
@@ -761,13 +732,12 @@
};
// Gets a collection of HTML chunks from the inptut textarea.
- this.getChunks = function () {
-
+ this.getChunks = function() {
var chunk = new Chunks();
chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
- chunk.startTag = "";
+ chunk.startTag = '';
chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
- chunk.endTag = "";
+ chunk.endTag = '';
chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
chunk.scrollTop = stateObj.scrollTop;
@@ -775,8 +745,7 @@
};
// Sets the TextareaState properties given a chunk of markdown.
- this.setChunks = function (chunk) {
-
+ this.setChunks = function(chunk) {
chunk.before = chunk.before + chunk.startTag;
chunk.after = chunk.endTag + chunk.after;
@@ -786,30 +755,27 @@
this.scrollTop = chunk.scrollTop;
};
this.init();
- };
-
- function PreviewManager(converter, panels, previewPushCallback) {
+ }
+ function PreviewManager(converter, panels, previewPushCallback) {
var managerObj = this;
var timeout;
var elapsedTime;
var oldInputText;
var maxDelay = 3000;
- var startType = "delayed"; // The other legal value is "manual"
+ var startType = 'delayed'; // The other legal value is "manual"
// Adds event listeners to elements
- var setupEvents = function (inputElem, listener) {
-
- util.addEvent(inputElem, "input", listener);
+ var setupEvents = function(inputElem, listener) {
+ util.addEvent(inputElem, 'input', listener);
inputElem.onpaste = listener;
inputElem.ondrop = listener;
- util.addEvent(inputElem, "keypress", listener);
- util.addEvent(inputElem, "keydown", listener);
+ util.addEvent(inputElem, 'keypress', listener);
+ util.addEvent(inputElem, 'keydown', listener);
};
- var getDocScrollTop = function () {
-
+ var getDocScrollTop = function() {
var result = 0;
if (window.innerHeight) {
@@ -827,8 +793,7 @@
return result;
};
- var makePreviewHtml = function () {
-
+ var makePreviewHtml = function() {
// If there is no registered preview panel
// there is nothing to do.
if (!panels.preview)
@@ -856,18 +821,16 @@
};
// setTimeout is already used. Used as an event listener.
- var applyTimeout = function () {
-
+ var applyTimeout = function() {
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
- if (startType !== "manual") {
-
+ if (startType !== 'manual') {
var delay = 0;
- if (startType === "delayed") {
+ if (startType === 'delayed') {
delay = elapsedTime;
}
@@ -878,23 +841,22 @@
}
};
- var getScaleFactor = function (panel) {
+ var getScaleFactor = function(panel) {
if (panel.scrollHeight <= panel.clientHeight) {
return 1;
}
return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
};
- var setPanelScrollTops = function () {
+ var setPanelScrollTops = function() {
if (panels.preview) {
panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview);
}
};
- this.refresh = function (requiresRefresh) {
-
+ this.refresh = function(requiresRefresh) {
if (requiresRefresh) {
- oldInputText = "";
+ oldInputText = '';
makePreviewHtml();
}
else {
@@ -902,7 +864,7 @@
}
};
- this.processingTime = function () {
+ this.processingTime = function() {
return elapsedTime;
};
@@ -911,7 +873,7 @@
// IE doesn't let you use innerHTML if the element is contained somewhere in a table
// (which is the case for inline editing) -- in that case, detach the element, set the
// value, and reattach. Yes, that *is* ridiculous.
- var ieSafePreviewSet = function (text) {
+ var ieSafePreviewSet = function(text) {
var preview = panels.preview;
var parent = preview.parentNode;
var sibling = preview.nextSibling;
@@ -921,15 +883,15 @@
parent.appendChild(preview);
else
parent.insertBefore(preview, sibling);
- }
+ };
- var nonSuckyBrowserPreviewSet = function (text) {
+ var nonSuckyBrowserPreviewSet = function(text) {
panels.preview.innerHTML = text;
- }
+ };
var previewSetter;
- var previewSet = function (text) {
+ var previewSet = function(text) {
if (previewSetter)
return previewSetter(text);
@@ -942,8 +904,7 @@
}
};
- var pushPreviewHtml = function (text) {
-
+ var pushPreviewHtml = function(text) {
var emptyTop = position.getTop(panels.input) - getDocScrollTop();
if (panels.preview) {
@@ -960,7 +921,7 @@
var fullTop = position.getTop(panels.input) - getDocScrollTop();
if (uaSniffed.isIE) {
- setTimeout(function () {
+ setTimeout(function() {
window.scrollBy(0, fullTop - emptyTop);
}, 0);
}
@@ -969,8 +930,7 @@
}
};
- var init = function () {
-
+ var init = function() {
setupEvents(panels.input, applyTimeout);
makePreviewHtml();
@@ -980,41 +940,40 @@
};
init();
- };
+ }
// Creates the background behind the hyperlink text entry box.
// And download dialog
// Most of this has been moved to CSS but the div creation and
// browser-specific hacks remain here.
- ui.createBackground = function () {
-
- var background = doc.createElement("div"),
+ ui.createBackground = function() {
+ var background = doc.createElement('div'),
style = background.style;
- background.className = "wmd-prompt-background";
+ background.className = 'wmd-prompt-background';
- style.position = "absolute";
- style.top = "0";
+ style.position = 'absolute';
+ style.top = '0';
- style.zIndex = "1000";
+ style.zIndex = '1000';
if (uaSniffed.isIE) {
- style.filter = "alpha(opacity=50)";
+ style.filter = 'alpha(opacity=50)';
}
else {
- style.opacity = "0.5";
+ style.opacity = '0.5';
}
var pageSize = position.getPageSize();
- style.height = pageSize[1] + "px";
+ style.height = pageSize[1] + 'px';
if (uaSniffed.isIE) {
style.left = doc.documentElement.scrollLeft;
style.width = doc.documentElement.clientWidth;
}
else {
- style.left = "0";
- style.width = "100%";
+ style.left = '0';
+ style.width = '100%';
}
doc.body.appendChild(background);
@@ -1029,7 +988,7 @@
// callback: The function which is executed when the prompt is dismissed, either via OK or Cancel.
// It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel
// was chosen).
- ui.prompt = function (title,
+ ui.prompt = function(title,
urlLabel,
urlHelp,
urlError,
@@ -1040,8 +999,7 @@
defaultInputText,
callback,
imageIsDecorativeLabel,
- imageUploadHandler) {
-
+ imageUploadHandler) {
// These variables need to be declared at this level since they are used
// in multiple functions.
var dialog, // The dialog box.
@@ -1054,14 +1012,14 @@
// Used as a keydown event handler. Esc dismisses the prompt.
// Key code 27 is ESC.
- var checkEscape = function (key) {
+ var checkEscape = function(key) {
var code = (key.charCode || key.keyCode);
if (code === 27) {
close(true);
}
};
- var clearFormErrorMessages = function () {
+ var clearFormErrorMessages = function() {
urlInput.classList.remove('has-error');
urlErrorMsg.style.display = 'none';
descInput.classList.remove('has-error');
@@ -1071,8 +1029,8 @@
// Dismisses the hyperlink input box.
// isCancel is true if we don't care about the input text.
// isCancel is false if we are going to keep the text.
- var close = function (isCancel) {
- util.removeEvent(doc.body, "keydown", checkEscape);
+ var close = function(isCancel) {
+ util.removeEvent(doc.body, 'keydown', checkEscape);
var url = urlInput.value.trim();
var description = descInput.value.trim();
@@ -1130,66 +1088,66 @@
};
// Create the text input box form/window.
- var createDialog = function () {
+ var createDialog = function() {
// The main dialog box.
- dialog = doc.createElement("div");
+ dialog = doc.createElement('div');
dialog.innerHTML = _.template(
- document.getElementById("customwmd-prompt-template").innerHTML)({
- title: title,
- uploadFieldClass: (imageUploadHandler ? 'file-upload' : ''),
- urlLabel: urlLabel,
- urlError: urlError,
- urlHelp: urlHelp,
- urlDescLabel: urlDescLabel,
- descError: urlDescError,
- urlDescHelp: urlDescHelp,
- urlDescHelpLink: urlDescHelpLink,
- okText: gettext("OK"),
- cancelText: gettext("Cancel"),
- chooseFileText: gettext("Choose File"),
- imageIsDecorativeLabel: imageIsDecorativeLabel,
- imageUploadHandler: imageUploadHandler
- });
- dialog.setAttribute("role", "dialog");
- dialog.setAttribute("tabindex", "-1");
- dialog.setAttribute("aria-labelledby", "editorDialogTitle");
- dialog.className = "wmd-prompt-dialog";
- dialog.style.padding = "10px;";
- dialog.style.position = "fixed";
- dialog.style.width = "500px";
- dialog.style.zIndex = "1001";
+ document.getElementById('customwmd-prompt-template').innerHTML)({
+ title: title,
+ uploadFieldClass: (imageUploadHandler ? 'file-upload' : ''),
+ urlLabel: urlLabel,
+ urlError: urlError,
+ urlHelp: urlHelp,
+ urlDescLabel: urlDescLabel,
+ descError: urlDescError,
+ urlDescHelp: urlDescHelp,
+ urlDescHelpLink: urlDescHelpLink,
+ okText: gettext('OK'),
+ cancelText: gettext('Cancel'),
+ chooseFileText: gettext('Choose File'),
+ imageIsDecorativeLabel: imageIsDecorativeLabel,
+ imageUploadHandler: imageUploadHandler
+ });
+ dialog.setAttribute('role', 'dialog');
+ dialog.setAttribute('tabindex', '-1');
+ dialog.setAttribute('aria-labelledby', 'editorDialogTitle');
+ dialog.className = 'wmd-prompt-dialog';
+ dialog.style.padding = '10px;';
+ dialog.style.position = 'fixed';
+ dialog.style.width = '500px';
+ dialog.style.zIndex = '1001';
doc.body.appendChild(dialog);
// This has to be done AFTER adding the dialog to the form if you
// want it to be centered.
- util.addEvent(doc.body, "keydown", checkEscape);
- dialog.style.top = "50%";
- dialog.style.left = "50%";
- dialog.style.display = "block";
+ util.addEvent(doc.body, 'keydown', checkEscape);
+ dialog.style.top = '50%';
+ dialog.style.left = '50%';
+ dialog.style.display = 'block';
if (uaSniffed.isIE_5or6) {
- dialog.style.position = "absolute";
- dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
- dialog.style.left = "50%";
+ dialog.style.position = 'absolute';
+ dialog.style.top = doc.documentElement.scrollTop + 200 + 'px';
+ dialog.style.left = '50%';
}
- dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
- dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
+ dialog.style.marginTop = -(position.getHeight(dialog) / 2) + 'px';
+ dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + 'px';
- urlInput = document.getElementById("new-url-input");
- urlErrorMsg = document.getElementById("new-url-input-field-message");
- descInput = document.getElementById("new-url-desc-input");
- descErrorMsg = document.getElementById("new-url-desc-input-field-message");
+ urlInput = document.getElementById('new-url-input');
+ urlErrorMsg = document.getElementById('new-url-input-field-message');
+ descInput = document.getElementById('new-url-desc-input');
+ descErrorMsg = document.getElementById('new-url-desc-input-field-message');
urlInput.value = defaultInputText;
- okButton = document.getElementById("new-link-image-ok");
- cancelButton = document.getElementById("new-link-image-cancel");
+ okButton = document.getElementById('new-link-image-ok');
+ cancelButton = document.getElementById('new-link-image-cancel');
- okButton.onclick = function () { return close(false); };
- cancelButton.onclick = function () { return close(true); };
+ okButton.onclick = function() { return close(false); };
+ cancelButton.onclick = function() { return close(true); };
- if(imageUploadHandler) {
- var startUploadHandler = function () {
- document.getElementById("file-upload").onchange = function() {
+ if (imageUploadHandler) {
+ var startUploadHandler = function() {
+ document.getElementById('file-upload').onchange = function() {
imageUploadHandler(this, urlInput);
urlInput.focus();
@@ -1198,17 +1156,17 @@
};
};
startUploadHandler();
- document.getElementById("file-upload-proxy").onclick = function () {
- document.getElementById("file-upload").click();
+ document.getElementById('file-upload-proxy').onclick = function() {
+ document.getElementById('file-upload').click();
return false;
};
- document.getElementById("img-is-decorative").onchange = function () {
+ document.getElementById('img-is-decorative').onchange = function() {
descInput.required = !descInput.required;
};
}
// trap focus in the dialog box
- $(dialog).on("keydown", function (event) {
+ $(dialog).on('keydown', function(event) {
// On tab backward from the first tabbable item in the prompt
if (event.which === 9 && event.shiftKey && event.target === urlInput) {
event.preventDefault();
@@ -1225,8 +1183,7 @@
// Why is this in a zero-length timeout?
// Is it working around a browser bug?
- setTimeout(function () {
-
+ setTimeout(function() {
createDialog();
var defTextLen = defaultInputText.length;
@@ -1237,8 +1194,8 @@
else if (urlInput.createTextRange) {
var range = urlInput.createTextRange();
range.collapse(false);
- range.moveStart("character", -defTextLen);
- range.moveEnd("character", defTextLen);
+ range.moveStart('character', -defTextLen);
+ range.moveEnd('character', defTextLen);
range.select();
}
@@ -1246,70 +1203,67 @@
}, 0);
};
- function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, imageUploadHandler) {
-
+ function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, imageUploadHandler) {
var inputBox = panels.input,
buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements.
makeSpritedButtonRow();
- var keyEvent = "keydown";
+ var keyEvent = 'keydown';
if (uaSniffed.isOpera) {
- keyEvent = "keypress";
+ keyEvent = 'keypress';
}
- util.addEvent(inputBox, keyEvent, function (key) {
-
+ util.addEvent(inputBox, keyEvent, function(key) {
// Check to see if we have a button key and, if so execute the callback.
- if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
-
+ if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
var keyCode = key.charCode || key.keyCode;
var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
switch (keyCodeStr) {
- case "b":
- doClick(buttons.bold);
- break;
- case "i":
- doClick(buttons.italic);
- break;
- case "l":
- doClick(buttons.link);
- break;
- case "q":
- doClick(buttons.quote);
- break;
- case "k":
- doClick(buttons.code);
- break;
- case "g":
- doClick(buttons.image);
- break;
- case "o":
- doClick(buttons.olist);
- break;
- case "u":
- doClick(buttons.ulist);
- break;
- case "h":
- doClick(buttons.heading);
- break;
- case "r":
- doClick(buttons.hr);
- break;
- case "y":
+ case 'b':
+ doClick(buttons.bold);
+ break;
+ case 'i':
+ doClick(buttons.italic);
+ break;
+ case 'l':
+ doClick(buttons.link);
+ break;
+ case 'q':
+ doClick(buttons.quote);
+ break;
+ case 'k':
+ doClick(buttons.code);
+ break;
+ case 'g':
+ doClick(buttons.image);
+ break;
+ case 'o':
+ doClick(buttons.olist);
+ break;
+ case 'u':
+ doClick(buttons.ulist);
+ break;
+ case 'h':
+ doClick(buttons.heading);
+ break;
+ case 'r':
+ doClick(buttons.hr);
+ break;
+ case 'y':
+ doClick(buttons.redo);
+ break;
+ case 'z':
+ if (key.shiftKey) {
doClick(buttons.redo);
- break;
- case "z":
- if (key.shiftKey) {
- doClick(buttons.redo);
- }
- else {
- doClick(buttons.undo);
- }
- break;
- default:
- return;
+ }
+ else {
+ doClick(buttons.undo);
+ }
+ break;
+ default:
+ return;
}
@@ -1324,13 +1278,13 @@
});
// Auto-indent on shift-enter
- util.addEvent(inputBox, "keyup", function (key) {
+ util.addEvent(inputBox, 'keyup', function(key) {
if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
var keyCode = key.charCode || key.keyCode;
// Character 13 is Enter
if (keyCode === 13) {
var fakeButton = {};
- fakeButton.textOp = bindCommand("doAutoindent");
+ fakeButton.textOp = bindCommand('doAutoindent');
doClick(fakeButton);
}
}
@@ -1338,7 +1292,7 @@
// special handler because IE clears the context of the textbox on ESC
if (uaSniffed.isIE) {
- util.addEvent(inputBox, "keydown", function (key) {
+ util.addEvent(inputBox, 'keydown', function(key) {
var code = key.keyCode;
if (code === 27) {
return false;
@@ -1348,12 +1302,10 @@
// Perform the button's action.
- function doClick(button) {
-
+ function doClick(button) {
inputBox.focus();
- if (button.textOp) {
-
+ if (button.textOp) {
if (undoManager) {
undoManager.setCommandMode();
}
@@ -1383,8 +1335,7 @@
// Yes this is awkward and I think it sucks, but there's
// no real workaround. Only the image and link code
// create dialogs and require the function pointers.
- var fixupInputArea = function () {
-
+ var fixupInputArea = function() {
inputBox.focus();
if (chunks) {
@@ -1399,36 +1350,34 @@
if (!noCleanup) {
fixupInputArea();
- }
-
+ }
}
if (button.execute) {
button.execute(undoManager);
}
- };
+ }
- function setupButton(button, isEnabled) {
-
- var normalYShift = "0px";
- var disabledYShift = "-20px";
- var highlightYShift = "-40px";
- var image = button.getElementsByTagName("span")[0];
+ function setupButton(button, isEnabled) {
+ var normalYShift = '0px';
+ var disabledYShift = '-20px';
+ var highlightYShift = '-40px';
+ var image = button.getElementsByTagName('span')[0];
if (isEnabled) {
- image.style.backgroundPosition = button.XShift + " " + normalYShift;
- button.onmouseover = function () {
- image.style.backgroundPosition = this.XShift + " " + highlightYShift;
+ image.style.backgroundPosition = button.XShift + ' ' + normalYShift;
+ button.onmouseover = function() {
+ image.style.backgroundPosition = this.XShift + ' ' + highlightYShift;
};
- button.onmouseout = function () {
- image.style.backgroundPosition = this.XShift + " " + normalYShift;
+ button.onmouseout = function() {
+ image.style.backgroundPosition = this.XShift + ' ' + normalYShift;
};
// IE tries to select the background image "button" text (it's
// implemented in a list item) so we have to cache the selection
// on mousedown.
if (uaSniffed.isIE) {
- button.onmousedown = function () {
+ button.onmousedown = function() {
if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection
return;
}
@@ -1438,14 +1387,14 @@
}
if (!button.isHelp) {
- button.onclick = function () {
+ button.onclick = function() {
if (this.onmouseout) {
this.onmouseout();
}
doClick(this);
return false;
- }
- util.addEvent(button, "keydown", function(event) {
+ };
+ util.addEvent(button, 'keydown', function(event) {
var keyCode = event.charCode || event.keyCode;
if (keyCode == 32 || keyCode == 13) {
if (event.preventDefault) {
@@ -1456,43 +1405,42 @@
}
doClick(button);
}
- })
+ });
}
}
else {
- image.style.backgroundPosition = button.XShift + " " + disabledYShift;
- button.onmouseover = button.onmouseout = button.onclick = function () { };
+ image.style.backgroundPosition = button.XShift + ' ' + disabledYShift;
+ button.onmouseover = button.onmouseout = button.onclick = function() { };
}
}
function bindCommand(method) {
- if (typeof method === "string")
+ if (typeof method === 'string')
method = commandManager[method];
- return function () { method.apply(commandManager, arguments); }
+ return function() { method.apply(commandManager, arguments); };
}
- function makeSpritedButtonRow() {
-
+ function makeSpritedButtonRow() {
var buttonBar = panels.buttonBar;
- var normalYShift = "0px";
- var disabledYShift = "-20px";
- var highlightYShift = "-40px";
+ var normalYShift = '0px';
+ var disabledYShift = '-20px';
+ var highlightYShift = '-40px';
- var buttonRow = document.createElement("div");
- buttonRow.setAttribute("role", "toolbar");
- buttonRow.id = "wmd-button-row" + postfix;
+ var buttonRow = document.createElement('div');
+ buttonRow.setAttribute('role', 'toolbar');
+ buttonRow.id = 'wmd-button-row' + postfix;
buttonRow.className = 'wmd-button-row';
buttonRow = buttonBar.appendChild(buttonRow);
var xPosition = 0;
- var makeButton = function (id, title, XShift, textOp) {
- var button = document.createElement("span");
- button.setAttribute("role", "button");
+ var makeButton = function(id, title, XShift, textOp) {
+ var button = document.createElement('span');
+ button.setAttribute('role', 'button');
button.tabIndex = 0;
- button.className = "wmd-button";
- button.style.left = xPosition + "px";
+ button.className = 'wmd-button';
+ button.style.left = xPosition + 'px';
xPosition += 25;
- var buttonImage = document.createElement("span");
+ var buttonImage = document.createElement('span');
button.id = id + postfix;
button.appendChild(buttonImage);
button.title = title;
@@ -1503,55 +1451,55 @@
buttonRow.appendChild(button);
return button;
};
- var makeSpacer = function (num) {
- var spacer = document.createElement("span");
- spacer.setAttribute("role", "separator");
- spacer.className = "wmd-spacer wmd-spacer" + num;
- spacer.id = "wmd-spacer" + num + postfix;
+ var makeSpacer = function(num) {
+ var spacer = document.createElement('span');
+ spacer.setAttribute('role', 'separator');
+ spacer.className = 'wmd-spacer wmd-spacer' + num;
+ spacer.id = 'wmd-spacer' + num + postfix;
buttonRow.appendChild(spacer);
xPosition += 25;
- }
+ };
- buttons.bold = makeButton("wmd-bold-button", gettext("Bold (Ctrl+B)"), "0px", bindCommand("doBold"));
- buttons.italic = makeButton("wmd-italic-button", gettext("Italic (Ctrl+I)"), "-20px", bindCommand("doItalic"));
+ buttons.bold = makeButton('wmd-bold-button', gettext('Bold (Ctrl+B)'), '0px', bindCommand('doBold'));
+ buttons.italic = makeButton('wmd-italic-button', gettext('Italic (Ctrl+I)'), '-20px', bindCommand('doItalic'));
makeSpacer(1);
- buttons.link = makeButton("wmd-link-button", gettext("Hyperlink (Ctrl+L)"), "-40px", bindCommand(function (chunk, postProcessing) {
+ buttons.link = makeButton('wmd-link-button', gettext('Hyperlink (Ctrl+L)'), '-40px', bindCommand(function(chunk, postProcessing) {
return this.doLinkOrImage(chunk, postProcessing, false);
}));
- buttons.quote = makeButton("wmd-quote-button", gettext("Blockquote (Ctrl+Q)"), "-60px", bindCommand("doBlockquote"));
- buttons.code = makeButton("wmd-code-button", gettext("Code Sample (Ctrl+K)"), "-80px", bindCommand("doCode"));
- buttons.image = makeButton("wmd-image-button", gettext("Image (Ctrl+G)"), "-100px", bindCommand(function (chunk, postProcessing) {
+ buttons.quote = makeButton('wmd-quote-button', gettext('Blockquote (Ctrl+Q)'), '-60px', bindCommand('doBlockquote'));
+ buttons.code = makeButton('wmd-code-button', gettext('Code Sample (Ctrl+K)'), '-80px', bindCommand('doCode'));
+ buttons.image = makeButton('wmd-image-button', gettext('Image (Ctrl+G)'), '-100px', bindCommand(function(chunk, postProcessing) {
return this.doLinkOrImage(chunk, postProcessing, true, imageUploadHandler);
}));
makeSpacer(2);
- buttons.olist = makeButton("wmd-olist-button", gettext("Numbered List (Ctrl+O)"), "-120px", bindCommand(function (chunk, postProcessing) {
+ buttons.olist = makeButton('wmd-olist-button', gettext('Numbered List (Ctrl+O)'), '-120px', bindCommand(function(chunk, postProcessing) {
this.doList(chunk, postProcessing, true);
}));
- buttons.ulist = makeButton("wmd-ulist-button", gettext("Bulleted List (Ctrl+U)"), "-140px", bindCommand(function (chunk, postProcessing) {
+ buttons.ulist = makeButton('wmd-ulist-button', gettext('Bulleted List (Ctrl+U)'), '-140px', bindCommand(function(chunk, postProcessing) {
this.doList(chunk, postProcessing, false);
}));
- buttons.heading = makeButton("wmd-heading-button", gettext("Heading (Ctrl+H)"), "-160px", bindCommand("doHeading"));
- buttons.hr = makeButton("wmd-hr-button", gettext("Horizontal Rule (Ctrl+R)"), "-180px", bindCommand("doHorizontalRule"));
+ buttons.heading = makeButton('wmd-heading-button', gettext('Heading (Ctrl+H)'), '-160px', bindCommand('doHeading'));
+ buttons.hr = makeButton('wmd-hr-button', gettext('Horizontal Rule (Ctrl+R)'), '-180px', bindCommand('doHorizontalRule'));
makeSpacer(3);
- buttons.undo = makeButton("wmd-undo-button", gettext("Undo (Ctrl+Z)"), "-200px", null);
- buttons.undo.execute = function (manager) { if (manager) manager.undo(); };
+ buttons.undo = makeButton('wmd-undo-button', gettext('Undo (Ctrl+Z)'), '-200px', null);
+ buttons.undo.execute = function(manager) { if (manager) manager.undo(); };
var redoTitle = /win/.test(nav.platform.toLowerCase()) ?
- gettext("Redo (Ctrl+Y)") :
- gettext("Redo (Ctrl+Shift+Z)"); // mac and other non-Windows platforms
+ gettext('Redo (Ctrl+Y)') :
+ gettext('Redo (Ctrl+Shift+Z)'); // mac and other non-Windows platforms
- buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null);
- buttons.redo.execute = function (manager) { if (manager) manager.redo(); };
+ buttons.redo = makeButton('wmd-redo-button', redoTitle, '-220px', null);
+ buttons.redo.execute = function(manager) { if (manager) manager.redo(); };
if (helpOptions) {
- var helpButton = document.createElement("span");
- var helpButtonImage = document.createElement("span");
+ var helpButton = document.createElement('span');
+ var helpButtonImage = document.createElement('span');
helpButton.appendChild(helpButtonImage);
- helpButton.className = "wmd-button wmd-help-button";
- helpButton.id = "wmd-help-button" + postfix;
- helpButton.XShift = "-240px";
+ helpButton.className = 'wmd-button wmd-help-button';
+ helpButton.id = 'wmd-help-button' + postfix;
+ helpButton.XShift = '-240px';
helpButton.isHelp = true;
- helpButton.style.right = "0px";
+ helpButton.style.right = '0px';
helpButton.title = helpOptions.title || defaultHelpHoverTitle;
helpButton.onclick = helpOptions.handler;
@@ -1568,10 +1516,9 @@
setupButton(buttons.undo, undoManager.canUndo());
setupButton(buttons.redo, undoManager.canRedo());
}
- };
-
- this.setUndoRedoButtonStates = setUndoRedoButtonStates;
+ }
+ this.setUndoRedoButtonStates = setUndoRedoButtonStates;
}
function CommandManager(pluginHooks) {
@@ -1581,45 +1528,44 @@
var commandProto = CommandManager.prototype;
// The markdown symbols - 4 spaces = code, > = blockquote, etc.
- commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
+ commandProto.prefixes = '(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)';
// Remove markdown symbols from the chunk selection.
- commandProto.unwrap = function (chunk) {
- var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g");
- chunk.selection = chunk.selection.replace(txt, "$1 $2");
+ commandProto.unwrap = function(chunk) {
+ var txt = new re('([^\\n])\\n(?!(\\n|' + this.prefixes + '))', 'g');
+ chunk.selection = chunk.selection.replace(txt, '$1 $2');
};
- commandProto.wrap = function (chunk, len) {
+ commandProto.wrap = function(chunk, len) {
this.unwrap(chunk);
- var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"),
+ var regex = new re('(.{1,' + len + '})( +|$\\n?)', 'gm'),
that = this;
- chunk.selection = chunk.selection.replace(regex, function (line, marked) {
- if (new re("^" + that.prefixes, "").test(line)) {
+ chunk.selection = chunk.selection.replace(regex, function(line, marked) {
+ if (new re('^' + that.prefixes, '').test(line)) {
return line;
}
- return marked + "\n";
+ return marked + '\n';
});
- chunk.selection = chunk.selection.replace(/\s+$/, "");
+ chunk.selection = chunk.selection.replace(/\s+$/, '');
};
- commandProto.doBold = function (chunk, postProcessing) {
- return this.doBorI(chunk, postProcessing, 2, gettext("strong text"));
+ commandProto.doBold = function(chunk, postProcessing) {
+ return this.doBorI(chunk, postProcessing, 2, gettext('strong text'));
};
- commandProto.doItalic = function (chunk, postProcessing) {
- return this.doBorI(chunk, postProcessing, 1, gettext("emphasized text"));
+ commandProto.doItalic = function(chunk, postProcessing) {
+ return this.doBorI(chunk, postProcessing, 1, gettext('emphasized text'));
};
// chunk: The selected region that will be enclosed with */**
// nStars: 1 for italics, 2 for bold
// insertText: If you just click the button without highlighting text, this gets inserted
- commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) {
-
+ commandProto.doBorI = function(chunk, postProcessing, nStars, insertText) {
// Get rid of whitespace and fixup newlines.
chunk.trimWhitespace();
- chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
+ chunk.selection = chunk.selection.replace(/\n{2,}/g, '\n');
// Look for stars before and after. Is the chunk already marked up?
// note that these regex matches cannot fail
@@ -1630,19 +1576,18 @@
// Remove stars if we have to since the button acts as a toggle.
if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
- chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
- chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
+ chunk.before = chunk.before.replace(re('[*]{' + nStars + '}$', ''), '');
+ chunk.after = chunk.after.replace(re('^[*]{' + nStars + '}', ''), '');
}
else if (!chunk.selection && starsAfter) {
// It's not really clear why this code is necessary. It just moves
// some arbitrary stuff around.
- chunk.after = chunk.after.replace(/^([*_]*)/, "");
- chunk.before = chunk.before.replace(/(\s?)$/, "");
+ chunk.after = chunk.after.replace(/^([*_]*)/, '');
+ chunk.before = chunk.before.replace(/(\s?)$/, '');
var whitespace = re.$1;
chunk.before = chunk.before + starsAfter + whitespace;
}
- else {
-
+ else {
// In most cases, if you don't have any selected text and click the button
// you'll get a selected, marked up region with the default text inserted.
if (!chunk.selection && !starsAfter) {
@@ -1650,7 +1595,7 @@
}
// Add the true markup.
- var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
+ var markup = nStars <= 1 ? '*' : '**'; // shouldn't the test be = ?
chunk.before = chunk.before + markup;
chunk.after = markup + chunk.after;
}
@@ -1658,24 +1603,22 @@
return;
};
- commandProto.stripLinkDefs = function (text, defsToAdd) {
-
+ commandProto.stripLinkDefs = function(text, defsToAdd) {
text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
- function (totalMatch, id, link, newlines, title) {
- defsToAdd[id] = totalMatch.replace(/\s*$/, "");
+ function(totalMatch, id, link, newlines, title) {
+ defsToAdd[id] = totalMatch.replace(/\s*$/, '');
if (newlines) {
// Strip the title and return that separately.
- defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
+ defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, '');
return newlines + title;
}
- return "";
+ return '';
});
return text;
};
- commandProto.addLinkDef = function (chunk, linkDef) {
-
+ commandProto.addLinkDef = function(chunk, linkDef) {
var refNumber = 0; // The current reference number
var defsToAdd = {}; //
// Start with a clean slate by removing all previous link definitions.
@@ -1683,13 +1626,13 @@
chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd);
chunk.after = this.stripLinkDefs(chunk.after, defsToAdd);
- var defs = "";
+ var defs = '';
var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
- var addDefNumber = function (def) {
+ var addDefNumber = function(def) {
refNumber++;
- def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
- defs += "\n" + def;
+ def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, ' [' + refNumber + ']:');
+ defs += '\n' + def;
};
// note that
@@ -1697,7 +1640,7 @@
// of regex, inner is always a proper substring of wholeMatch, and
// b) more than one level of nesting is neither supported by the regex
// nor making a lot of sense (the only use case for nesting is a linked image)
- var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
+ var getLink = function(wholeMatch, before, inner, afterInner, id, end) {
inner = inner.replace(regex, getLink);
if (defsToAdd[id]) {
addDefNumber(defsToAdd[id]);
@@ -1720,13 +1663,13 @@
chunk.after = chunk.after.replace(regex, getLink);
if (chunk.after) {
- chunk.after = chunk.after.replace(/\n*$/, "");
+ chunk.after = chunk.after.replace(/\n*$/, '');
}
if (!chunk.after) {
- chunk.selection = chunk.selection.replace(/\n*$/, "");
+ chunk.selection = chunk.selection.replace(/\n*$/, '');
}
- chunk.after += "\n\n" + defs;
+ chunk.after += '\n\n' + defs;
return refOut;
};
@@ -1734,42 +1677,39 @@
// takes the line as entered into the add link/as image dialog and makes
// sure the URL and the optinal title are "nice".
function properlyEncoded(linkdef) {
- return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) {
- link = link.replace(/\?.*$/, function (querypart) {
- return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical
+ return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function(wholematch, link, title) {
+ link = link.replace(/\?.*$/, function(querypart) {
+ return querypart.replace(/\+/g, ' '); // in the query string, a plus and a space are identical
});
link = decodeURIComponent(link); // unencode first, to prevent double encoding
link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
- link = link.replace(/\?.*$/, function (querypart) {
- return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
+ link = link.replace(/\?.*$/, function(querypart) {
+ return querypart.replace(/\+/g, '%2b'); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
});
if (title) {
- title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, "");
- title = $.trim(title).replace(/"/g, "quot;").replace(/\(/g, "(").replace(/\)/g, ")").replace(//g, ">");
+ title = title.trim ? title.trim() : title.replace(/^\s*/, '').replace(/\s*$/, '');
+ title = $.trim(title).replace(/"/g, 'quot;').replace(/\(/g, '(').replace(/\)/g, ')').replace(//g, '>');
}
return title ? link + ' "' + title + '"' : link;
});
}
- commandProto.doLinkOrImage = function (chunk, postProcessing, isImage, imageUploadHandler) {
+ commandProto.doLinkOrImage = function(chunk, postProcessing, isImage, imageUploadHandler) {
chunk.trimWhitespace();
chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
var background;
- if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
-
- chunk.startTag = chunk.startTag.replace(/!?\[/, "");
- chunk.endTag = "";
- this.addLinkDef(chunk, null);
-
+ if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
+ chunk.startTag = chunk.startTag.replace(/!?\[/, '');
+ chunk.endTag = '';
+ this.addLinkDef(chunk, null);
}
- else {
-
+ else {
// We're moving start and end tag back into the selection, since (as we're in the else block) we're not
// *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the
// link text. linkEnteredCallback takes care of escaping any brackets.
chunk.selection = chunk.startTag + chunk.selection + chunk.endTag;
- chunk.startTag = chunk.endTag = "";
+ chunk.startTag = chunk.endTag = '';
if (/\n\n/.test(chunk.selection)) {
this.addLinkDef(chunk, null);
@@ -1778,7 +1718,7 @@
var that = this;
// The function to be executed when you enter a link and press OK or Cancel.
// Marks up the link and adds the ref.
- var linkEnteredCallback = function (link, description) {
+ var linkEnteredCallback = function(link, description) {
background.parentNode.removeChild(background);
if (link !== null) {
@@ -1800,20 +1740,20 @@
// this by anchoring with ^, because in the case that the selection starts with two brackets, this
// would mean a zero-width match at the start. Since zero-width matches advance the string position,
// the first bracket could then not act as the "not a backslash" for the second.
- chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1);
+ chunk.selection = (' ' + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, '$1\\').substr(1);
- var linkDef = " [999]: " + properlyEncoded(link);
+ var linkDef = ' [999]: ' + properlyEncoded(link);
var num = that.addLinkDef(chunk, linkDef);
- chunk.startTag = isImage ? "![" : "[";
- chunk.endTag = "][" + num + "]";
+ chunk.startTag = isImage ? '![' : '[';
+ chunk.endTag = '][' + num + ']';
if (!chunk.selection) {
if (isImage) {
- chunk.selection = description ? description : "";
+ chunk.selection = description ? description : '';
}
else {
- chunk.selection = description ? description : gettext("enter link description here");
+ chunk.selection = description ? description : gettext('enter link description here');
}
}
}
@@ -1860,23 +1800,22 @@
// When making a list, hitting shift-enter will put your cursor on the next line
// at the current indent level.
- commandProto.doAutoindent = function (chunk, postProcessing) {
-
+ commandProto.doAutoindent = function(chunk, postProcessing) {
var commandMgr = this,
fakeSelection = false;
- chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
- chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
- chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
+ chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, '\n\n');
+ chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, '\n\n');
+ chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, '\n\n');
// There's no selection, end the cursor wasn't at the end of the line:
// The user wants to split the current list item / code line / blockquote line
// (for the latter it doesn't really matter) in two. Temporarily select the
// (rest of the) line to achieve this.
if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
- chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) {
+ chunk.after = chunk.after.replace(/^[^\n]*/, function(wholeMatch) {
chunk.selection = wholeMatch;
- return "";
+ return '';
});
fakeSelection = true;
}
@@ -1899,27 +1838,26 @@
if (fakeSelection) {
chunk.after = chunk.selection + chunk.after;
- chunk.selection = "";
+ chunk.selection = '';
}
};
- commandProto.doBlockquote = function (chunk, postProcessing) {
-
+ commandProto.doBlockquote = function(chunk, postProcessing) {
chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
- function (totalMatch, newlinesBefore, text, newlinesAfter) {
+ function(totalMatch, newlinesBefore, text, newlinesAfter) {
chunk.before += newlinesBefore;
chunk.after = newlinesAfter + chunk.after;
return text;
});
chunk.before = chunk.before.replace(/(>[ \t]*)$/,
- function (totalMatch, blankLine) {
+ function(totalMatch, blankLine) {
chunk.selection = blankLine + chunk.selection;
- return "";
+ return '';
});
- chunk.selection = chunk.selection.replace(/^(\s|>)+$/, "");
- chunk.selection = chunk.selection || gettext("Blockquote");
+ chunk.selection = chunk.selection.replace(/^(\s|>)+$/, '');
+ chunk.selection = chunk.selection || gettext('Blockquote');
// The original code uses a regular expression to find out how much of the
// text *directly before* the selection already was a blockquote:
@@ -1951,11 +1889,11 @@
// Hence we replaced this by a simple state machine that just goes through the
// lines and checks for a), b), and c).
- var match = "",
- leftOver = "",
+ var match = '',
+ leftOver = '',
line;
if (chunk.before) {
- var lines = chunk.before.replace(/\n$/, "").split("\n");
+ var lines = chunk.before.replace(/\n$/, '').split('\n');
var inChain = false;
for (var i = 0; i < lines.length; i++) {
var good = false;
@@ -1971,15 +1909,15 @@
good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
}
if (good) {
- match += line + "\n";
+ match += line + '\n';
} else {
leftOver += match + line;
- match = "\n";
+ match = '\n';
}
}
if (!/(^|\n)>/.test(match)) { // d)
leftOver += match;
- match = "";
+ match = '';
}
}
@@ -1989,50 +1927,49 @@
// end of change
if (chunk.after) {
- chunk.after = chunk.after.replace(/^\n?/, "\n");
+ chunk.after = chunk.after.replace(/^\n?/, '\n');
}
chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
- function (totalMatch) {
+ function(totalMatch) {
chunk.endTag = totalMatch;
- return "";
+ return '';
}
);
- var replaceBlanksInTags = function (useBracket) {
-
- var replacement = useBracket ? "> " : "";
+ var replaceBlanksInTags = function(useBracket) {
+ var replacement = useBracket ? '> ' : '';
if (chunk.startTag) {
chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
- function (totalMatch, markdown) {
- return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
+ function(totalMatch, markdown) {
+ return '\n' + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + '\n';
});
}
if (chunk.endTag) {
chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
- function (totalMatch, markdown) {
- return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
+ function(totalMatch, markdown) {
+ return '\n' + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + '\n';
});
}
};
if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) {
this.wrap(chunk, SETTINGS.lineLength - 2);
- chunk.selection = chunk.selection.replace(/^/gm, "> ");
+ chunk.selection = chunk.selection.replace(/^/gm, '> ');
replaceBlanksInTags(true);
chunk.skipLines();
} else {
- chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
+ chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, '');
this.unwrap(chunk);
replaceBlanksInTags(false);
if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) {
- chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
+ chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, '\n\n');
}
if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) {
- chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n");
+ chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, '\n\n');
}
}
@@ -2040,26 +1977,24 @@
if (!/\n/.test(chunk.selection)) {
chunk.selection = chunk.selection.replace(/^(> *)/,
- function (wholeMatch, blanks) {
+ function(wholeMatch, blanks) {
chunk.startTag += blanks;
- return "";
+ return '';
});
}
};
- commandProto.doCode = function (chunk, postProcessing) {
-
+ commandProto.doCode = function(chunk, postProcessing) {
var hasTextBefore = /\S[ ]*$/.test(chunk.before);
var hasTextAfter = /^[ ]*\S/.test(chunk.after);
// Use 'four space' markdown if the selection is on its own
// line or is multiline.
- if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
-
+ if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
chunk.before = chunk.before.replace(/[ ]{4}$/,
- function (totalMatch) {
+ function(totalMatch) {
chunk.selection = totalMatch + chunk.selection;
- return "";
+ return '';
});
var nLinesBack = 1;
@@ -2075,18 +2010,18 @@
chunk.skipLines(nLinesBack, nLinesForward);
if (!chunk.selection) {
- chunk.startTag = " ";
- chunk.selection = gettext("enter code here");
+ chunk.startTag = ' ';
+ chunk.selection = gettext('enter code here');
}
else {
if (/^[ ]{0,3}\S/m.test(chunk.selection)) {
if (/\n/.test(chunk.selection))
- chunk.selection = chunk.selection.replace(/^/gm, " ");
+ chunk.selection = chunk.selection.replace(/^/gm, ' ');
else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior
- chunk.before += " ";
+ chunk.before += ' ';
}
else {
- chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
+ chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, '');
}
}
}
@@ -2097,23 +2032,22 @@
chunk.findTags(/`/, /`/);
if (!chunk.startTag && !chunk.endTag) {
- chunk.startTag = chunk.endTag = "`";
+ chunk.startTag = chunk.endTag = '`';
if (!chunk.selection) {
- chunk.selection = gettext("enter code here");
+ chunk.selection = gettext('enter code here');
}
}
else if (chunk.endTag && !chunk.startTag) {
chunk.before += chunk.endTag;
- chunk.endTag = "";
+ chunk.endTag = '';
}
else {
- chunk.startTag = chunk.endTag = "";
+ chunk.startTag = chunk.endTag = '';
}
}
};
- commandProto.doList = function (chunk, postProcessing, isNumberedList) {
-
+ commandProto.doList = function(chunk, postProcessing, isNumberedList) {
// These are identical except at the very beginning and end.
// Should probably use the regex extension function to make this clearer.
var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
@@ -2122,27 +2056,26 @@
// The default bullet is a dash but others are possible.
// This has nothing to do with the particular HTML bullet,
// it's just a markdown bullet.
- var bullet = "-";
+ var bullet = '-';
// The number in a numbered list.
var num = 1;
// Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
- var getItemPrefix = function () {
+ var getItemPrefix = function() {
var prefix;
if (isNumberedList) {
- prefix = " " + num + ". ";
+ prefix = ' ' + num + '. ';
num++;
}
else {
- prefix = " " + bullet + " ";
+ prefix = ' ' + bullet + ' ';
}
return prefix;
};
// Fixes the prefixes of the other list items.
- var getPrefixedItem = function (itemText) {
-
+ var getPrefixedItem = function(itemText) {
// The numbering flag is unset when called by autoindent.
if (isNumberedList === undefined) {
isNumberedList = /^\s*\d/.test(itemText);
@@ -2150,7 +2083,7 @@
// Renumber/bullet the list element.
itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
- function (_) {
+ function(_) {
return getItemPrefix();
});
@@ -2161,14 +2094,13 @@
if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) {
chunk.before += chunk.startTag;
- chunk.startTag = "";
+ chunk.startTag = '';
}
- if (chunk.startTag) {
-
+ if (chunk.startTag) {
var hasDigits = /\d+[.]/.test(chunk.startTag);
- chunk.startTag = "";
- chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
+ chunk.startTag = '';
+ chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, '\n');
this.unwrap(chunk);
chunk.skipLines();
@@ -2184,7 +2116,7 @@
var nLinesUp = 1;
chunk.before = chunk.before.replace(previousItemsRegex,
- function (itemText) {
+ function(itemText) {
if (/^\s*([*+-])/.test(itemText)) {
bullet = re.$1;
}
@@ -2193,7 +2125,7 @@
});
if (!chunk.selection) {
- chunk.selection = gettext("List item");
+ chunk.selection = gettext('List item');
}
var prefix = getItemPrefix();
@@ -2201,7 +2133,7 @@
var nLinesDown = 1;
chunk.after = chunk.after.replace(nextItemsRegex,
- function (itemText) {
+ function(itemText) {
nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
return getPrefixedItem(itemText);
});
@@ -2209,24 +2141,22 @@
chunk.trimWhitespace(true);
chunk.skipLines(nLinesUp, nLinesDown, true);
chunk.startTag = prefix;
- var spaces = prefix.replace(/./g, " ");
+ var spaces = prefix.replace(/./g, ' ');
this.wrap(chunk, SETTINGS.lineLength - spaces.length);
- chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
-
+ chunk.selection = chunk.selection.replace(/\n/g, '\n' + spaces);
};
- commandProto.doHeading = function (chunk, postProcessing) {
-
+ commandProto.doHeading = function(chunk, postProcessing) {
// Remove leading/trailing whitespace and reduce internal spaces to single spaces.
- chunk.selection = chunk.selection.replace(/\s+/g, " ");
- chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
+ chunk.selection = chunk.selection.replace(/\s+/g, ' ');
+ chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, '');
// If we clicked the button with no selected text, we just
// make a level 2 hash header around some default text.
if (!chunk.selection) {
- chunk.startTag = "## ";
- chunk.selection = gettext("Heading");
- chunk.endTag = " ##";
+ chunk.startTag = '## ';
+ chunk.selection = gettext('Heading');
+ chunk.endTag = ' ##';
return;
}
@@ -2237,7 +2167,7 @@
if (/#+/.test(chunk.startTag)) {
headerLevel = re.lastMatch.length;
}
- chunk.startTag = chunk.endTag = "";
+ chunk.startTag = chunk.endTag = '';
// Try to get the current header level by looking for - and = in the line
// below the selection.
@@ -2250,7 +2180,7 @@
}
// Skip to the next line so we can create the header markdown.
- chunk.startTag = chunk.endTag = "";
+ chunk.startTag = chunk.endTag = '';
chunk.skipLines(1, 1);
// We make a level 2 header if there is no current header.
@@ -2258,27 +2188,24 @@
// If it's already a level 1 header, it's removed.
var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
- if (headerLevelToCreate > 0) {
-
+ if (headerLevelToCreate > 0) {
// The button only creates level 1 and 2 underline headers.
// Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
- var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
+ var headerChar = headerLevelToCreate >= 2 ? '-' : '=';
var len = chunk.selection.length;
if (len > SETTINGS.lineLength) {
len = SETTINGS.lineLength;
}
- chunk.endTag = "\n";
+ chunk.endTag = '\n';
while (len--) {
chunk.endTag += headerChar;
}
}
};
- commandProto.doHorizontalRule = function (chunk, postProcessing) {
- chunk.startTag = "----------\n";
- chunk.selection = "";
+ commandProto.doHorizontalRule = function(chunk, postProcessing) {
+ chunk.startTag = '----------\n';
+ chunk.selection = '';
chunk.skipLines(2, 1, true);
- }
-
-
+ };
})();
diff --git a/lms/static/js/Markdown.Sanitizer.js b/lms/static/js/Markdown.Sanitizer.js
index cc5826fa8f..221673eb59 100644
--- a/lms/static/js/Markdown.Sanitizer.js
+++ b/lms/static/js/Markdown.Sanitizer.js
@@ -1,19 +1,19 @@
-(function () {
+(function() {
var output, Converter;
- if (typeof exports === "object" && typeof require === "function") { // we're in a CommonJS (e.g. Node.js) module
+ if (typeof exports === 'object' && typeof require === 'function') { // we're in a CommonJS (e.g. Node.js) module
output = exports;
- Converter = require("./Markdown.Converter").Converter;
+ Converter = require('./Markdown.Converter').Converter;
} else {
output = window.Markdown;
Converter = output.Converter;
}
-
- output.getSanitizingConverter = function () {
+
+ output.getSanitizingConverter = function() {
var converter = new Converter();
- converter.hooks.chain("postConversion", sanitizeHtml);
- converter.hooks.chain("postConversion", balanceTags);
+ converter.hooks.chain('postConversion', sanitizeHtml);
+ converter.hooks.chain('postConversion', balanceTags);
return converter;
- }
+ };
function sanitizeHtml(html) {
return html.replace(/<[^>]*>?/gi, sanitizeTag);
@@ -31,21 +31,20 @@
if (tag.match(basic_tag_whitelist) || tag.match(a_white) || tag.match(img_white))
return tag;
else
- return "";
+ return '';
}
- ///
- /// attempt to balance HTML tags in the html string
- /// by removing any unmatched opening or closing tags
- /// IMPORTANT: we *assume* HTML has *already* been
- /// sanitized and is safe/sane before balancing!
- ///
- /// adapted from CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593
- ///
+ // /
+ // / attempt to balance HTML tags in the html string
+ // / by removing any unmatched opening or closing tags
+ // / IMPORTANT: we *assume* HTML has *already* been
+ // / sanitized and is safe/sane before balancing!
+ // /
+ // / adapted from CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593
+ // /
function balanceTags(html) {
-
- if (html == "")
- return "";
+ if (html == '')
+ return '';
var re = /<\/?\w+[^>]*(\s|$|>)/g;
// convert everything to lower case; this makes
@@ -58,7 +57,7 @@
return html;
var tagname, tag;
- var ignoredtags = "![]()
";
+ var ignoredtags = '![]()
';
var match;
var tagpaired = [];
var tagremove = [];
@@ -66,10 +65,10 @@
// loop through matched tags in forward order
for (var ctag = 0; ctag < tagcount; ctag++) {
- tagname = tags[ctag].replace(/<\/?(\w+).*/, "$1");
+ tagname = tags[ctag].replace(/<\/?(\w+).*/, '$1');
// skip any already paired tags
// and skip tags in our ignore list; assume they're self-closed
- if (tagpaired[ctag] || ignoredtags.search("<" + tagname + ">") > -1)
+ if (tagpaired[ctag] || ignoredtags.search('<' + tagname + '>') > -1)
continue;
tag = tags[ctag];
@@ -79,7 +78,7 @@
// this is an opening tag
// search forwards (next tags), look for closing tags
for (var ntag = ctag + 1; ntag < tagcount; ntag++) {
- if (!tagpaired[ntag] && tags[ntag] == "" + tagname + ">") {
+ if (!tagpaired[ntag] && tags[ntag] == '' + tagname + '>') {
match = ntag;
break;
}
@@ -98,8 +97,8 @@
// delete all orphaned tags from the string
var ctag = 0;
- html = html.replace(re, function (match) {
- var res = tagremove[ctag] ? "" : match;
+ html = html.replace(re, function(match) {
+ var res = tagremove[ctag] ? '' : match;
ctag++;
return res;
});
diff --git a/lms/static/js/ajax-error.js b/lms/static/js/ajax-error.js
index 6b29d4c24b..b25164d2b8 100644
--- a/lms/static/js/ajax-error.js
+++ b/lms/static/js/ajax-error.js
@@ -1,15 +1,15 @@
-$(document).ajaxError(function (event, jXHR) {
+$(document).ajaxError(function(event, jXHR) {
if (jXHR.status === 403 && jXHR.responseText === 'Unauthenticated') {
var message = gettext(
- 'You have been logged out of your edX account. '+
- 'Click Okay to log in again now. '+
- 'Click Cancel to stay on this page '+
+ 'You have been logged out of your edX account. ' +
+ 'Click Okay to log in again now. ' +
+ 'Click Cancel to stay on this page ' +
'(you must log in again to save your work).'
);
if (window.confirm(message)) {
var currentLocation = window.location.pathname;
window.location.href = '/login?next=' + encodeURIComponent(currentLocation);
- };
+ }
}
});
diff --git a/lms/static/js/api_admin/catalog_preview_factory.js b/lms/static/js/api_admin/catalog_preview_factory.js
index df7c931e86..3db93cfb3f 100644
--- a/lms/static/js/api_admin/catalog_preview_factory.js
+++ b/lms/static/js/api_admin/catalog_preview_factory.js
@@ -1,12 +1,12 @@
-;(function (define) {
+(function(define) {
'use strict';
- define(['js/api_admin/views/catalog_preview'], function (CatalogPreviewView) {
- return function (options) {
+ define(['js/api_admin/views/catalog_preview'], function(CatalogPreviewView) {
+ return function(options) {
var view = new CatalogPreviewView({
el: '.catalog-body',
previewUrl: options.previewUrl,
- catalogApiUrl: options.catalogApiUrl,
+ catalogApiUrl: options.catalogApiUrl
});
return view.render();
};
diff --git a/lms/static/js/api_admin/views/catalog_preview.js b/lms/static/js/api_admin/views/catalog_preview.js
index f32110aa71..866d92f37f 100644
--- a/lms/static/js/api_admin/views/catalog_preview.js
+++ b/lms/static/js/api_admin/views/catalog_preview.js
@@ -1,4 +1,4 @@
-;(function(define) {
+(function(define) {
'use strict';
define([
@@ -7,21 +7,21 @@
'gettext',
'text!../../../templates/api_admin/catalog-results.underscore',
'text!../../../templates/api_admin/catalog-error.underscore'
- ], function (Backbone, _, gettext, catalogResultsTpl, catalogErrorTpl) {
+ ], function(Backbone, _, gettext, catalogResultsTpl, catalogErrorTpl) {
return Backbone.View.extend({
events: {
'click .preview-query': 'previewQuery'
},
- initialize: function (options) {
+ initialize: function(options) {
this.previewUrl = options.previewUrl;
this.catalogApiUrl = options.catalogApiUrl;
},
- render: function () {
+ render: function() {
this.$('#id_query').after(
- ''
+ ''
);
return this;
},
@@ -29,8 +29,8 @@
/*
* Return the user's query, URL-encoded.
*/
- getQuery: function () {
- return encodeURIComponent(this.$("#id_query").val());
+ getQuery: function() {
+ return encodeURIComponent(this.$('#id_query').val());
},
/*
@@ -38,12 +38,12 @@
* with the user's query. On success, displays the
* results, and on failure, displays an error message.
*/
- previewQuery: function (event) {
+ previewQuery: function(event) {
event.preventDefault();
$.ajax(this.previewUrl + '?q=' + this.getQuery(), {
method: 'GET',
success: _.bind(this.renderCourses, this),
- error: _.bind(function () {
+ error: _.bind(function() {
this.$('.preview-results').html(_.template(catalogErrorTpl)({}));
}, this)
});
@@ -53,12 +53,12 @@
* Render a list of courses with data returned by the
* courses API.
*/
- renderCourses: function (data) {
+ renderCourses: function(data) {
this.$('.preview-results').html(_.template(catalogResultsTpl)({
'courses': data.results,
- 'catalogApiUrl': this.catalogApiUrl,
+ 'catalogApiUrl': this.catalogApiUrl
}));
- },
+ }
});
});
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/bookmarks/collections/bookmarks.js b/lms/static/js/bookmarks/collections/bookmarks.js
index 8da8c24ed7..ffedc9ef2a 100644
--- a/lms/static/js/bookmarks/collections/bookmarks.js
+++ b/lms/static/js/bookmarks/collections/bookmarks.js
@@ -1,29 +1,28 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'backbone',
'edx-ui-toolkit/js/pagination/paging-collection',
'js/bookmarks/models/bookmark'
- ], function (Backbone, PagingCollection, BookmarkModel) {
- return PagingCollection.extend({
- model: BookmarkModel,
+ ], function(Backbone, PagingCollection, BookmarkModel) {
+ return PagingCollection.extend({
+ model: BookmarkModel,
- queryParams: {
- course_id: function () { return this.options.course_id; },
- fields : function () { return 'display_name,path'; }
- },
+ queryParams: {
+ course_id: function() { return this.options.course_id; },
+ fields: function() { return 'display_name,path'; }
+ },
- url: function() {
- return this.url;
- },
+ url: function() {
+ return this.url;
+ },
- constructor: function (models, options) {
- this.options = options;
- this.url = options.url;
- PagingCollection.prototype.constructor.call(this, models, options);
- }
- });
+ constructor: function(models, options) {
+ this.options = options;
+ this.url = options.url;
+ PagingCollection.prototype.constructor.call(this, models, options);
+ }
+ });
});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/bookmarks/models/bookmark.js b/lms/static/js/bookmarks/models/bookmark.js
index 57c50c30e5..3f0e7c6e17 100644
--- a/lms/static/js/bookmarks/models/bookmark.js
+++ b/lms/static/js/bookmarks/models/bookmark.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
- define(['backbone'], function (Backbone) {
-
+ define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
idAttribute: 'id',
defaults: {
@@ -12,10 +11,9 @@
created: ''
},
- blockUrl: function () {
+ blockUrl: function() {
return '/courses/' + this.get('course_id') + '/jump_to/' + this.get('usage_id');
}
});
});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/bookmarks/views/bookmark_button.js b/lms/static/js/bookmarks/views/bookmark_button.js
index fd2574e156..642e184020 100644
--- a/lms/static/js/bookmarks/views/bookmark_button.js
+++ b/lms/static/js/bookmarks/views/bookmark_button.js
@@ -1,115 +1,114 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'js/views/message_banner'],
- function (gettext, $, _, Backbone, MessageBannerView) {
+ function(gettext, $, _, Backbone, MessageBannerView) {
+ return Backbone.View.extend({
+ errorMessage: gettext('An error has occurred. Please try again.'),
- return Backbone.View.extend({
- errorMessage: gettext('An error has occurred. Please try again.'),
+ srAddBookmarkText: gettext('Click to add'),
+ srRemoveBookmarkText: gettext('Click to remove'),
- srAddBookmarkText: gettext('Click to add'),
- srRemoveBookmarkText: gettext('Click to remove'),
+ events: {
+ 'click': 'toggleBookmark'
+ },
- events: {
- 'click': 'toggleBookmark'
- },
+ showBannerInterval: 5000, // time in ms
- showBannerInterval: 5000, // time in ms
+ initialize: function(options) {
+ this.apiUrl = options.apiUrl;
+ this.bookmarkId = options.bookmarkId;
+ this.bookmarked = options.bookmarked;
+ this.usageId = options.usageId;
+ this.setBookmarkState(this.bookmarked);
+ },
- initialize: function (options) {
- this.apiUrl = options.apiUrl;
- this.bookmarkId = options.bookmarkId;
- this.bookmarked = options.bookmarked;
- this.usageId = options.usageId;
- this.setBookmarkState(this.bookmarked);
- },
+ toggleBookmark: function(event) {
+ event.preventDefault();
- toggleBookmark: function(event) {
- event.preventDefault();
+ this.$el.prop('disabled', true);
- this.$el.prop('disabled', true);
+ if (this.$el.hasClass('bookmarked')) {
+ this.removeBookmark();
+ } else {
+ this.addBookmark();
+ }
+ },
- if (this.$el.hasClass('bookmarked')) {
- this.removeBookmark();
- } else {
- this.addBookmark();
- }
- },
-
- addBookmark: function() {
- var view = this;
- $.ajax({
- data: {usage_id: view.usageId},
- type: "POST",
- url: view.apiUrl,
- dataType: 'json',
- success: function () {
- view.$el.trigger('bookmark:add');
- view.setBookmarkState(true);
- },
- error: function (jqXHR) {
- try {
- var response = jqXHR.responseText ? JSON.parse(jqXHR.responseText) : '';
- var userMessage = response ? response.user_message : '';
- view.showError(userMessage);
- }
- catch(err) {
+ addBookmark: function() {
+ var view = this;
+ $.ajax({
+ data: {usage_id: view.usageId},
+ type: 'POST',
+ url: view.apiUrl,
+ dataType: 'json',
+ success: function() {
+ view.$el.trigger('bookmark:add');
+ view.setBookmarkState(true);
+ },
+ error: function(jqXHR) {
+ try {
+ var response = jqXHR.responseText ? JSON.parse(jqXHR.responseText) : '';
+ var userMessage = response ? response.user_message : '';
+ view.showError(userMessage);
+ }
+ catch (err) {
view.showError();
}
- },
- complete: function () {
- view.$el.prop('disabled', false);
- }
- });
- },
-
- removeBookmark: function() {
- var view = this;
- var deleteUrl = view.apiUrl + view.bookmarkId + '/';
-
- $.ajax({
- type: "DELETE",
- url: deleteUrl,
- success: function () {
- view.$el.trigger('bookmark:remove');
- view.setBookmarkState(false);
- },
- error: function() {
- view.showError();
- },
- complete: function() {
- view.$el.prop('disabled', false);
- }
- });
- },
-
- setBookmarkState: function(bookmarked) {
- if (bookmarked) {
- this.$el.addClass('bookmarked');
- this.$el.attr('aria-pressed', 'true');
- this.$el.find('.bookmark-sr').text(this.srRemoveBookmarkText);
- } else {
- this.$el.removeClass('bookmarked');
- this.$el.attr('aria-pressed', 'false');
- this.$el.find('.bookmark-sr').text(this.srAddBookmarkText);
- }
- },
-
- showError: function (errorText) {
- var errorMsg = errorText || this.errorMessage;
-
- if (!this.messageView) {
- this.messageView = new MessageBannerView({
- el: $('.message-banner'),
- type: 'error'
+ },
+ complete: function() {
+ view.$el.prop('disabled', false);
+ }
});
- }
- this.messageView.showMessage(errorMsg);
+ },
+
+ removeBookmark: function() {
+ var view = this;
+ var deleteUrl = view.apiUrl + view.bookmarkId + '/';
+
+ $.ajax({
+ type: 'DELETE',
+ url: deleteUrl,
+ success: function() {
+ view.$el.trigger('bookmark:remove');
+ view.setBookmarkState(false);
+ },
+ error: function() {
+ view.showError();
+ },
+ complete: function() {
+ view.$el.prop('disabled', false);
+ }
+ });
+ },
+
+ setBookmarkState: function(bookmarked) {
+ if (bookmarked) {
+ this.$el.addClass('bookmarked');
+ this.$el.attr('aria-pressed', 'true');
+ this.$el.find('.bookmark-sr').text(this.srRemoveBookmarkText);
+ } else {
+ this.$el.removeClass('bookmarked');
+ this.$el.attr('aria-pressed', 'false');
+ this.$el.find('.bookmark-sr').text(this.srAddBookmarkText);
+ }
+ },
+
+ showError: function(errorText) {
+ var errorMsg = errorText || this.errorMessage;
+
+ if (!this.messageView) {
+ this.messageView = new MessageBannerView({
+ el: $('.message-banner'),
+ type: 'error'
+ });
+ }
+ this.messageView.showMessage(errorMsg);
// Hide message automatically after some interval
- setTimeout(_.bind(function () {
- this.messageView.hideMessage();
- }, this), this.showBannerInterval);
- }
+ setTimeout(_.bind(function() {
+ this.messageView.hideMessage();
+ }, this), this.showBannerInterval);
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/bookmarks/views/bookmarks_list.js b/lms/static/js/bookmarks/views/bookmarks_list.js
index 38a7688d9a..18db4360a3 100644
--- a/lms/static/js/bookmarks/views/bookmarks_list.js
+++ b/lms/static/js/bookmarks/views/bookmarks_list.js
@@ -1,133 +1,132 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'logger', 'moment', 'edx-ui-toolkit/js/utils/html-utils',
'common/js/components/views/paging_header', 'common/js/components/views/paging_footer',
'text!templates/bookmarks/bookmarks-list.underscore'
],
- function (gettext, $, _, Backbone, Logger, _moment, HtmlUtils,
+ function(gettext, $, _, Backbone, Logger, _moment, HtmlUtils,
PagingHeaderView, PagingFooterView, BookmarksListTemplate) {
+ var moment = _moment || window.moment;
- var moment = _moment || window.moment;
+ return Backbone.View.extend({
- return Backbone.View.extend({
+ el: '.courseware-results',
+ coursewareContentEl: '#course-content',
+ coursewareResultsWrapperEl: '.courseware-results-wrapper',
- el: '.courseware-results',
- coursewareContentEl: '#course-content',
- coursewareResultsWrapperEl: '.courseware-results-wrapper',
+ errorIcon: '',
+ loadingIcon: '',
- errorIcon: '',
- loadingIcon: '',
+ errorMessage: gettext('An error has occurred. Please try again.'),
+ loadingMessage: gettext('Loading'),
- errorMessage: gettext('An error has occurred. Please try again.'),
- loadingMessage: gettext('Loading'),
+ defaultPage: 1,
- defaultPage: 1,
+ events: {
+ 'click .bookmarks-results-list-item': 'visitBookmark'
+ },
- events : {
- 'click .bookmarks-results-list-item': 'visitBookmark'
- },
+ initialize: function(options) {
+ this.template = HtmlUtils.template(BookmarksListTemplate);
+ this.loadingMessageView = options.loadingMessageView;
+ this.errorMessageView = options.errorMessageView;
+ this.langCode = $(this.el).data('langCode');
+ this.pagingHeaderView = new PagingHeaderView({collection: this.collection});
+ this.pagingFooterView = new PagingFooterView({collection: this.collection});
+ this.listenTo(this.collection, 'page_changed', this.render);
+ _.bindAll(this, 'render', 'humanFriendlyDate');
+ },
- initialize: function (options) {
- this.template = HtmlUtils.template(BookmarksListTemplate);
- this.loadingMessageView = options.loadingMessageView;
- this.errorMessageView = options.errorMessageView;
- this.langCode = $(this.el).data('langCode');
- this.pagingHeaderView = new PagingHeaderView({collection: this.collection});
- this.pagingFooterView = new PagingFooterView({collection: this.collection});
- this.listenTo(this.collection, 'page_changed', this.render);
- _.bindAll(this, 'render', 'humanFriendlyDate');
- },
+ render: function() {
+ var data = {
+ bookmarksCollection: this.collection,
+ humanFriendlyDate: this.humanFriendlyDate
+ };
- render: function () {
- var data = {
- bookmarksCollection: this.collection,
- humanFriendlyDate: this.humanFriendlyDate
- };
+ HtmlUtils.setHtml(this.$el, this.template(data));
+ this.pagingHeaderView.setElement(this.$('.paging-header')).render();
+ this.pagingFooterView.setElement(this.$('.paging-footer')).render();
+ this.delegateEvents();
+ return this;
+ },
- HtmlUtils.setHtml(this.$el, this.template(data));
- this.pagingHeaderView.setElement(this.$('.paging-header')).render();
- this.pagingFooterView.setElement(this.$('.paging-footer')).render();
- this.delegateEvents();
- return this;
- },
+ showBookmarks: function() {
+ var view = this;
- showBookmarks: function () {
- var view = this;
+ this.hideErrorMessage();
+ this.showBookmarksContainer();
- this.hideErrorMessage();
- this.showBookmarksContainer();
+ this.collection.getPage(this.defaultPage).done(function() {
+ view.render();
+ view.focusBookmarksElement();
+ }).fail(function() {
+ view.showErrorMessage();
+ });
+ },
- this.collection.getPage(this.defaultPage).done(function () {
- view.render();
- view.focusBookmarksElement();
- }).fail(function () {
- view.showErrorMessage();
- });
- },
-
- visitBookmark: function (event) {
- var bookmarkedComponent = $(event.currentTarget);
- var bookmark_id = bookmarkedComponent.data('bookmarkId');
- var component_usage_id = bookmarkedComponent.data('usageId');
- var component_type = bookmarkedComponent.data('componentType');
- Logger.log(
+ visitBookmark: function(event) {
+ var bookmarkedComponent = $(event.currentTarget);
+ var bookmark_id = bookmarkedComponent.data('bookmarkId');
+ var component_usage_id = bookmarkedComponent.data('usageId');
+ var component_type = bookmarkedComponent.data('componentType');
+ Logger.log(
'edx.bookmark.accessed',
- {
- bookmark_id: bookmark_id,
- component_type: component_type,
- component_usage_id: component_usage_id
- }
- ).always(function () {
+ {
+ bookmark_id: bookmark_id,
+ component_type: component_type,
+ component_usage_id: component_usage_id
+ }
+ ).always(function() {
window.location.href = event.currentTarget.pathname;
});
- },
+ },
/**
* Convert ISO 8601 formatted date into human friendly format. e.g, `2014-05-23T14:00:00Z` to `May 23, 2014`
* @param {String} isoDate - ISO 8601 formatted date string.
*/
- humanFriendlyDate: function (isoDate) {
- moment.locale(this.langCode);
- return moment(isoDate).format('LL');
- },
+ humanFriendlyDate: function(isoDate) {
+ moment.locale(this.langCode);
+ return moment(isoDate).format('LL');
+ },
- areBookmarksVisible: function () {
- return this.$('#my-bookmarks').is(":visible");
- },
+ areBookmarksVisible: function() {
+ return this.$('#my-bookmarks').is(':visible');
+ },
- hideBookmarks: function () {
- this.$el.hide();
- $(this.coursewareResultsWrapperEl).hide();
- $(this.coursewareContentEl).css( 'display', 'table-cell');
- },
+ hideBookmarks: function() {
+ this.$el.hide();
+ $(this.coursewareResultsWrapperEl).hide();
+ $(this.coursewareContentEl).css('display', 'table-cell');
+ },
- showBookmarksContainer: function () {
- $(this.coursewareContentEl).hide();
+ showBookmarksContainer: function() {
+ $(this.coursewareContentEl).hide();
// Empty el if it's not empty to get the clean state.
- this.$el.html('');
- this.$el.show();
- $(this.coursewareResultsWrapperEl).css('display', 'table-cell');
- },
+ this.$el.html('');
+ this.$el.show();
+ $(this.coursewareResultsWrapperEl).css('display', 'table-cell');
+ },
- showLoadingMessage: function () {
- this.loadingMessageView.showMessage(this.loadingMessage, this.loadingIcon);
- },
+ showLoadingMessage: function() {
+ this.loadingMessageView.showMessage(this.loadingMessage, this.loadingIcon);
+ },
- hideLoadingMessage: function () {
- this.loadingMessageView.hideMessage();
- },
+ hideLoadingMessage: function() {
+ this.loadingMessageView.hideMessage();
+ },
- showErrorMessage: function () {
- this.errorMessageView.showMessage(this.errorMessage, this.errorIcon);
- },
+ showErrorMessage: function() {
+ this.errorMessageView.showMessage(this.errorMessage, this.errorIcon);
+ },
- hideErrorMessage: function () {
- this.errorMessageView.hideMessage();
- },
+ hideErrorMessage: function() {
+ this.errorMessageView.hideMessage();
+ },
- focusBookmarksElement: function () {
- this.$('#my-bookmarks').focus();
- }
+ focusBookmarksElement: function() {
+ this.$('#my-bookmarks').focus();
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/bookmarks/views/bookmarks_list_button.js b/lms/static/js/bookmarks/views/bookmarks_list_button.js
index 0227e285c9..6fb74e6543 100644
--- a/lms/static/js/bookmarks/views/bookmarks_list_button.js
+++ b/lms/static/js/bookmarks/views/bookmarks_list_button.js
@@ -1,47 +1,46 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'js/bookmarks/views/bookmarks_list',
'js/bookmarks/collections/bookmarks', 'js/views/message_banner'],
- function (gettext, $, _, Backbone, BookmarksListView, BookmarksCollection, MessageBannerView) {
+ function(gettext, $, _, Backbone, BookmarksListView, BookmarksCollection, MessageBannerView) {
+ return Backbone.View.extend({
- return Backbone.View.extend({
+ el: '.courseware-bookmarks-button',
- el: '.courseware-bookmarks-button',
+ loadingMessageElement: '#loading-message',
+ errorMessageElement: '#error-message',
- loadingMessageElement: '#loading-message',
- errorMessageElement: '#error-message',
+ events: {
+ 'click .bookmarks-list-button': 'toggleBookmarksListView'
+ },
- events: {
- 'click .bookmarks-list-button': 'toggleBookmarksListView'
- },
-
- initialize: function () {
- var bookmarksCollection = new BookmarksCollection([],
- {
- course_id: $('.courseware-results').data('courseId'),
- url: $('.courseware-bookmarks-button').data('bookmarksApiUrl')
- }
+ initialize: function() {
+ var bookmarksCollection = new BookmarksCollection([],
+ {
+ course_id: $('.courseware-results').data('courseId'),
+ url: $('.courseware-bookmarks-button').data('bookmarksApiUrl')
+ }
);
- this.bookmarksListView = new BookmarksListView(
- {
- collection: bookmarksCollection,
- loadingMessageView: new MessageBannerView({el: $(this.loadingMessageElement)}),
- errorMessageView: new MessageBannerView({el: $(this.errorMessageElement)})
- }
+ this.bookmarksListView = new BookmarksListView(
+ {
+ collection: bookmarksCollection,
+ loadingMessageView: new MessageBannerView({el: $(this.loadingMessageElement)}),
+ errorMessageView: new MessageBannerView({el: $(this.errorMessageElement)})
+ }
);
- },
+ },
- toggleBookmarksListView: function () {
- if (this.bookmarksListView.areBookmarksVisible()) {
- this.bookmarksListView.hideBookmarks();
- this.$('.bookmarks-list-button').attr('aria-pressed', 'false');
- this.$('.bookmarks-list-button').removeClass('is-active').addClass('is-inactive');
- } else {
- this.bookmarksListView.showBookmarks();
- this.$('.bookmarks-list-button').attr('aria-pressed', 'true');
- this.$('.bookmarks-list-button').removeClass('is-inactive').addClass('is-active');
+ toggleBookmarksListView: function() {
+ if (this.bookmarksListView.areBookmarksVisible()) {
+ this.bookmarksListView.hideBookmarks();
+ this.$('.bookmarks-list-button').attr('aria-pressed', 'false');
+ this.$('.bookmarks-list-button').removeClass('is-active').addClass('is-inactive');
+ } else {
+ this.bookmarksListView.showBookmarks();
+ this.$('.bookmarks-list-button').attr('aria-pressed', 'true');
+ this.$('.bookmarks-list-button').removeClass('is-inactive').addClass('is-active');
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/ccx/schedule.js b/lms/static/js/ccx/schedule.js
index eb643e45d9..0fd2a75496 100644
--- a/lms/static/js/ccx/schedule.js
+++ b/lms/static/js/ccx/schedule.js
@@ -1,535 +1,535 @@
var edx = edx || {};
(function($, _, Backbone, gettext) {
- 'use strict';
+ 'use strict';
- edx.ccx = edx.ccx || {};
- edx.ccx.schedule = edx.ccx.schedule || {};
- var self;
+ edx.ccx = edx.ccx || {};
+ edx.ccx.schedule = edx.ccx.schedule || {};
+ var self;
- edx.ccx.schedule.reloadPage = function() {
- location.reload();
- };
+ edx.ccx.schedule.reloadPage = function() {
+ location.reload();
+ };
- edx.ccx.schedule.UnitModel = Backbone.Model.extend({
- defaults: {
- location: '',
- display_name: '',
- start: null,
- due: null,
- category: '',
- hidden: false,
- children: []
- }
- });
+ edx.ccx.schedule.UnitModel = Backbone.Model.extend({
+ defaults: {
+ location: '',
+ display_name: '',
+ start: null,
+ due: null,
+ category: '',
+ hidden: false,
+ children: []
+ }
+ });
- edx.ccx.schedule.Schedule = Backbone.Collection.extend({
- model: edx.ccx.schedule.UnitModel,
- url: 'ccx_schedule'
- });
+ edx.ccx.schedule.Schedule = Backbone.Collection.extend({
+ model: edx.ccx.schedule.UnitModel,
+ url: 'ccx_schedule'
+ });
- edx.ccx.schedule.ScheduleView = Backbone.View.extend({
+ edx.ccx.schedule.ScheduleView = Backbone.View.extend({
- initialize: function() {
- _.bindAll(this, 'render');
- this.schedule_collection = new edx.ccx.schedule.Schedule();
- this.schedule = {};
- this.schedule_collection.bind('reset', this.render);
- this.schedule_collection.fetch({reset: true});
- this.chapter_select = $('form#add-unit select[name="chapter"]');
- this.sequential_select = $('form#add-unit select[name="sequential"]');
- this.vertical_select = $('form#add-unit select[name="vertical"]');
- this.dirty = false;
- self = this;
- $('#add-all').on('click', function(event) {
- event.preventDefault();
- self.schedule_apply(self.schedule, self.show);
- self.dirty = true;
- self.schedule_collection.set(self.schedule);
- self.render();
- });
+ initialize: function() {
+ _.bindAll(this, 'render');
+ this.schedule_collection = new edx.ccx.schedule.Schedule();
+ this.schedule = {};
+ this.schedule_collection.bind('reset', this.render);
+ this.schedule_collection.fetch({reset: true});
+ this.chapter_select = $('form#add-unit select[name="chapter"]');
+ this.sequential_select = $('form#add-unit select[name="sequential"]');
+ this.vertical_select = $('form#add-unit select[name="vertical"]');
+ this.dirty = false;
+ self = this;
+ $('#add-all').on('click', function(event) {
+ event.preventDefault();
+ self.schedule_apply(self.schedule, self.show);
+ self.dirty = true;
+ self.schedule_collection.set(self.schedule);
+ self.render();
+ });
// By default input date and time fileds are disable.
- self.disableFields($('.ccx_due_date_time_fields'));
- self.disableFields($('.ccx_start_date_time_fields'));
+ self.disableFields($('.ccx_due_date_time_fields'));
+ self.disableFields($('.ccx_start_date_time_fields'));
// Add unit handlers
- this.chapter_select.on('change', function() {
- var chapter_location = self.chapter_select.val();
- self.vertical_select.html('').prop('disabled', true);
- if (chapter_location !== 'none') {
- var chapter = self.find_unit(self.hidden, chapter_location);
- self.sequential_select.html('')
- .append('')
+ this.chapter_select.on('change', function() {
+ var chapter_location = self.chapter_select.val();
+ self.vertical_select.html('').prop('disabled', true);
+ if (chapter_location !== 'none') {
+ var chapter = self.find_unit(self.hidden, chapter_location);
+ self.sequential_select.html('')
+ .append('')
.append(self.schedule_options(chapter.children));
- self.sequential_select.prop('disabled', false);
- $('#add-unit-button').prop('disabled', false);
+ self.sequential_select.prop('disabled', false);
+ $('#add-unit-button').prop('disabled', false);
// When a chapter is selected, start date fields are enabled and due date
// fields are disabled because due dates are not applicable on a chapter.
- self.disableFields($('.ccx_due_date_time_fields'));
- self.enableFields($('.ccx_start_date_time_fields'));
- } else {
- self.sequential_select.html('').prop('disabled', true);
+ self.disableFields($('.ccx_due_date_time_fields'));
+ self.enableFields($('.ccx_start_date_time_fields'));
+ } else {
+ self.sequential_select.html('').prop('disabled', true);
// When no chapter is selected, all date fields are disabled.
- self.disableFields($('.ccx_due_date_time_fields'));
- self.disableFields($('.ccx_start_date_time_fields'));
- }
- });
+ self.disableFields($('.ccx_due_date_time_fields'));
+ self.disableFields($('.ccx_start_date_time_fields'));
+ }
+ });
- this.sequential_select.on('change', function() {
- var sequential_location = self.sequential_select.val();
- if (sequential_location !== 'all') {
- var chapter = self.chapter_select.val(),
- sequential = self.find_unit(self.hidden, chapter, sequential_location);
- self.vertical_select.html('')
- .append('')
+ this.sequential_select.on('change', function() {
+ var sequential_location = self.sequential_select.val();
+ if (sequential_location !== 'all') {
+ var chapter = self.chapter_select.val(),
+ sequential = self.find_unit(self.hidden, chapter, sequential_location);
+ self.vertical_select.html('')
+ .append('')
.append(self.schedule_options(sequential.children));
- self.vertical_select.prop('disabled', false);
- self.set_datetime('start', sequential.start);
- self.set_datetime('due', sequential.due);
+ self.vertical_select.prop('disabled', false);
+ self.set_datetime('start', sequential.start);
+ self.set_datetime('due', sequential.due);
// When a subsection (aka sequential) is selected,
// both start and due date fields are enabled.
- self.enableFields($('.ccx_due_date_time_fields'));
- self.enableFields($('.ccx_start_date_time_fields'));
- } else {
+ self.enableFields($('.ccx_due_date_time_fields'));
+ self.enableFields($('.ccx_start_date_time_fields'));
+ } else {
// When "All subsections" is selected, all date fields are disabled.
- self.vertical_select.html('').prop('disabled', true);
- self.disableFields($('.ccx_due_date_time_fields'));
- self.enableFields($('.ccx_start_date_time_fields'));
- }
- });
+ self.vertical_select.html('').prop('disabled', true);
+ self.disableFields($('.ccx_due_date_time_fields'));
+ self.enableFields($('.ccx_start_date_time_fields'));
+ }
+ });
- this.vertical_select.on('change', function() {
- var vertical_location = self.vertical_select.val();
- if (vertical_location !== 'all') {
- var chapter = self.chapter_select.val(),
- sequential = self.sequential_select.val();
- var vertical = self.find_unit(
+ this.vertical_select.on('change', function() {
+ var vertical_location = self.vertical_select.val();
+ if (vertical_location !== 'all') {
+ var chapter = self.chapter_select.val(),
+ sequential = self.sequential_select.val();
+ var vertical = self.find_unit(
self.hidden, chapter, sequential, vertical_location);
// When a unit (aka vertical) is selected, all date fields are disabled because units
// inherit dates from subsection
- self.disableFields($('.ccx_due_date_time_fields'));
- self.disableFields($('.ccx_start_date_time_fields'));
- } else {
+ self.disableFields($('.ccx_due_date_time_fields'));
+ self.disableFields($('.ccx_start_date_time_fields'));
+ } else {
// When "All units" is selected, all date fields are enabled,
// because units inherit dates from subsections and we
// are showing dates from the selected subsection.
- self.enableFields($('.ccx_due_date_time_fields'));
- self.enableFields($('.ccx_start_date_time_fields'));
- }
- });
+ self.enableFields($('.ccx_due_date_time_fields'));
+ self.enableFields($('.ccx_start_date_time_fields'));
+ }
+ });
// Add unit handler
- $('#add-unit-button').on('click', function(event) {
- event.preventDefault();
+ $('#add-unit-button').on('click', function(event) {
+ event.preventDefault();
// Default value of time is 00:00.
- var start, chapter, sequential, vertical, units, due;
- start = self.get_datetime('start');
- chapter = self.chapter_select.val();
- sequential = self.sequential_select.val();
- vertical = self.vertical_select.val();
- units = self.find_lineage(
+ var start, chapter, sequential, vertical, units, due;
+ start = self.get_datetime('start');
+ chapter = self.chapter_select.val();
+ sequential = self.sequential_select.val();
+ vertical = self.vertical_select.val();
+ units = self.find_lineage(
self.schedule,
chapter,
sequential === 'all' ? null : sequential,
vertical === 'all' ? null : vertical
);
- due = self.get_datetime('due');
- var errorMessage = self.valid_dates(start, due);
- if (_.isUndefined(errorMessage)) {
- units.map(self.show);
- var unit = units[units.length - 1];
- if (!_.isUndefined(unit)) {
- if (!_.isNull(start)) {
- unit.start = start;
- }
- if (!_.isNull(due)) {
- unit.due = due;
- }
- }
- self.schedule_apply([unit], self.show);
- self.schedule_collection.set(self.schedule);
- self.dirty = true;
- self.render();
- } else {
- self.dirty = false;
- $('#ccx_schedule_error_message').text(errorMessage);
- $('#ajax-error').show().focus();
- $('#dirty-schedule').hide();
- }
- });
+ due = self.get_datetime('due');
+ var errorMessage = self.valid_dates(start, due);
+ if (_.isUndefined(errorMessage)) {
+ units.map(self.show);
+ var unit = units[units.length - 1];
+ if (!_.isUndefined(unit)) {
+ if (!_.isNull(start)) {
+ unit.start = start;
+ }
+ if (!_.isNull(due)) {
+ unit.due = due;
+ }
+ }
+ self.schedule_apply([unit], self.show);
+ self.schedule_collection.set(self.schedule);
+ self.dirty = true;
+ self.render();
+ } else {
+ self.dirty = false;
+ $('#ccx_schedule_error_message').text(errorMessage);
+ $('#ajax-error').show().focus();
+ $('#dirty-schedule').hide();
+ }
+ });
// Handle save button
- $('#dirty-schedule #save-changes').on('click', function(event) {
- event.preventDefault();
- self.save();
- });
- }, // end initialization
+ $('#dirty-schedule #save-changes').on('click', function(event) {
+ event.preventDefault();
+ self.save();
+ });
+ }, // end initialization
- render: function() {
- self.schedule = this.schedule_collection.toJSON();
- self.hidden = this.pruned(self.schedule, function(node) {
- return node.hidden || node.category !== 'vertical';
- });
- this.showing = this.pruned(self.schedule, function(node) {
- return !node.hidden;
- });
+ render: function() {
+ self.schedule = this.schedule_collection.toJSON();
+ self.hidden = this.pruned(self.schedule, function(node) {
+ return node.hidden || node.category !== 'vertical';
+ });
+ this.showing = this.pruned(self.schedule, function(node) {
+ return !node.hidden;
+ });
// schedule_template defined globally in ccx\schedule.html
/* globals schedule_template */
- this.$el.html(schedule_template({chapters: this.showing}));
- $('table.ccx-schedule .sequential,.vertical').hide();
- $('table.ccx-schedule .unit .toggle-collapse').on('click', this.toggle_collapse);
+ this.$el.html(schedule_template({chapters: this.showing}));
+ $('table.ccx-schedule .sequential,.vertical').hide();
+ $('table.ccx-schedule .unit .toggle-collapse').on('click', this.toggle_collapse);
// Hidden hover fields for empty date fields
- $('table.ccx-schedule .date button').each(function() {
- if ($(this).text().trim() === gettext("Click to change")) {
- $(this).html('Set date ' +
- gettext("Click to change") + '');
- }
- });
+ $('table.ccx-schedule .date button').each(function() {
+ if ($(this).text().trim() === gettext('Click to change')) {
+ $(this).html('Set date ' +
+ gettext('Click to change') + '');
+ }
+ });
// Handle date edit clicks
- $('table.ccx-schedule .date button').attr('href', '#enter-date-modal')
+ $('table.ccx-schedule .date button').attr('href', '#enter-date-modal')
.leanModal({closeButton: '.close-modal'});
- $('table.ccx-schedule .due-date button').on('click', this.enterNewDate('due'));
- $('table.ccx-schedule .start-date button').on('click', this.enterNewDate('start'));
+ $('table.ccx-schedule .due-date button').on('click', this.enterNewDate('due'));
+ $('table.ccx-schedule .start-date button').on('click', this.enterNewDate('start'));
// click handler for expand all
- $('#ccx_expand_all_btn').on('click', self.expandAll);
+ $('#ccx_expand_all_btn').on('click', self.expandAll);
// click handler for collapse all
- $('#ccx_collapse_all_btn').on('click', self.collapseAll);
+ $('#ccx_collapse_all_btn').on('click', self.collapseAll);
// Click handler for remove all
- $('table.ccx-schedule button#remove-all').on('click', function(event) {
- event.preventDefault();
- self.schedule_apply(self.schedule, self.hide);
- self.dirty = true;
- self.schedule_collection.set(self.schedule);
- self.render();
- });
+ $('table.ccx-schedule button#remove-all').on('click', function(event) {
+ event.preventDefault();
+ self.schedule_apply(self.schedule, self.hide);
+ self.dirty = true;
+ self.schedule_collection.set(self.schedule);
+ self.render();
+ });
// Remove unit handler
- $('table.ccx-schedule button.remove-unit').on('click', function() {
- var row = $(this).closest('tr'),
- path = row.data('location').split(' '),
- unit = self.find_unit(self.schedule, path[0], path[1], path[2]);
- self.schedule_apply([unit], self.hide);
- self.schedule_collection.set(self.schedule);
- self.dirty = true;
- self.render();
- });
+ $('table.ccx-schedule button.remove-unit').on('click', function() {
+ var row = $(this).closest('tr'),
+ path = row.data('location').split(' '),
+ unit = self.find_unit(self.schedule, path[0], path[1], path[2]);
+ self.schedule_apply([unit], self.hide);
+ self.schedule_collection.set(self.schedule);
+ self.dirty = true;
+ self.render();
+ });
// Show or hide form
- if (this.hidden.length) {
+ if (this.hidden.length) {
// Populate chapters select, depopulate others
- this.chapter_select.html('')
- .append('')
+ this.chapter_select.html('')
+ .append('')
.append(self.schedule_options(this.hidden));
- this.sequential_select.html('').prop('disabled', true);
- this.vertical_select.html('').prop('disabled', true);
- $('form#add-unit').show();
- $('#all-units-added').hide();
- $('#add-unit-button').prop('disabled', true);
- } else {
- $('form#add-unit').hide();
- $('#all-units-added').show();
- }
+ this.sequential_select.html('').prop('disabled', true);
+ this.vertical_select.html('').prop('disabled', true);
+ $('form#add-unit').show();
+ $('#all-units-added').hide();
+ $('#add-unit-button').prop('disabled', true);
+ } else {
+ $('form#add-unit').hide();
+ $('#all-units-added').show();
+ }
// Show or hide save button
- if (this.dirty) {
- $('#dirty-schedule').show();
- $('html, body').animate(
- { scrollTop: $('#dirty-schedule').offset().top },
- 'slow', function() {$('#dirty-schedule').focus();
- });
- } else {
- $('#dirty-schedule').hide();
- }
- $('#ajax-error').hide();
+ if (this.dirty) {
+ $('#dirty-schedule').show();
+ $('html, body').animate(
+ {scrollTop: $('#dirty-schedule').offset().top},
+ 'slow', function() { $('#dirty-schedule').focus();
+ });
+ } else {
+ $('#dirty-schedule').hide();
+ }
+ $('#ajax-error').hide();
- return this;
- }, // end render
+ return this;
+ }, // end render
- save: function() {
- self.schedule_collection.set(self.schedule);
- var button = $('#dirty-schedule #save-changes');
- button.prop('disabled', true).text(gettext("Saving"));
+ save: function() {
+ self.schedule_collection.set(self.schedule);
+ var button = $('#dirty-schedule #save-changes');
+ button.prop('disabled', true).text(gettext('Saving'));
// save_url defined globally in ccx\schedule.html
/* globals save_url */
- $.ajax({
- url: save_url,
- type: 'POST',
- contentType: 'application/json',
- data: JSON.stringify(self.schedule),
- success: function(data) {
- self.dirty = false;
- self.render();
- button.prop('disabled', false).text(gettext("Save changes"));
+ $.ajax({
+ url: save_url,
+ type: 'POST',
+ contentType: 'application/json',
+ data: JSON.stringify(self.schedule),
+ success: function(data) {
+ self.dirty = false;
+ self.render();
+ button.prop('disabled', false).text(gettext('Save changes'));
// Update textarea with grading policy JSON, since grading policy
// may have changed.
- $('#grading-policy').text(data.grading_policy);
+ $('#grading-policy').text(data.grading_policy);
+ },
+ error: function(jqXHR) {
+ console.log(jqXHR.responseText);
+ $('#ajax-error').show().focus();
+ $('#dirty-schedule').hide();
+ $('form#add-unit select,input,button').prop('disabled', true);
+ button.prop('disabled', false).text(gettext('Save changes'));
+ }
+ });
+ }, // end save
+
+ hide: function(unit) {
+ if (unit !== undefined) {
+ unit.hidden = true;
+ }
},
- error: function(jqXHR) {
- console.log(jqXHR.responseText);
- $('#ajax-error').show().focus();
- $('#dirty-schedule').hide();
- $('form#add-unit select,input,button').prop('disabled', true);
- button.prop('disabled', false).text(gettext("Save changes"));
- }
- });
- }, // end save
- hide: function(unit) {
- if (unit !== undefined) {
- unit.hidden = true;
- }
- },
+ show: function(unit) {
+ if (unit !== undefined) {
+ unit.hidden = false;
+ }
+ },
- show: function(unit) {
- if (unit !== undefined) {
- unit.hidden = false;
- }
- },
-
- valid_dates: function(start, due) {
- var errorMessage;
+ valid_dates: function(start, due) {
+ var errorMessage;
// Start date is compulsory and due date is optional.
- if (_.isEmpty(start) && !_.isEmpty(due)) {
- errorMessage = gettext("Please enter valid start date and time.");
- } else if (!_.isEmpty(start) && !_.isEmpty(due)) {
- var requirejs = window.require || RequireJS.require;
- var moment = requirejs("moment");
- var parsedDueDate = moment(due, 'YYYY-MM-DD HH:mm');
- var parsedStartDate = moment(start, 'YYYY-MM-DD HH:mm');
- if (parsedDueDate.isBefore(parsedStartDate)) {
- errorMessage = gettext("Due date cannot be before start date.");
- }
- }
- return errorMessage;
- },
+ if (_.isEmpty(start) && !_.isEmpty(due)) {
+ errorMessage = gettext('Please enter valid start date and time.');
+ } else if (!_.isEmpty(start) && !_.isEmpty(due)) {
+ var requirejs = window.require || RequireJS.require;
+ var moment = requirejs('moment');
+ var parsedDueDate = moment(due, 'YYYY-MM-DD HH:mm');
+ var parsedStartDate = moment(start, 'YYYY-MM-DD HH:mm');
+ if (parsedDueDate.isBefore(parsedStartDate)) {
+ errorMessage = gettext('Due date cannot be before start date.');
+ }
+ }
+ return errorMessage;
+ },
- get_datetime: function(which) {
- var date = $('form#add-unit input[name=' + which + '_date]').val();
- var time = $('form#add-unit input[name=' + which + '_time]').val();
- time = _.isEmpty(time) ? "00:00" : time;
- if (date && time) {
- return date + ' ' + time;
- }
- return null;
- },
+ get_datetime: function(which) {
+ var date = $('form#add-unit input[name=' + which + '_date]').val();
+ var time = $('form#add-unit input[name=' + which + '_time]').val();
+ time = _.isEmpty(time) ? '00:00' : time;
+ if (date && time) {
+ return date + ' ' + time;
+ }
+ return null;
+ },
- set_datetime: function(which, value) {
- var parts = value ? value.split(' ') : ['', ''],
- date = parts[0],
- time = parts[1];
- $('form#add-unit input[name=' + which + '_date]').val(date);
- $('form#add-unit input[name=' + which + '_time]').val(time);
- },
+ set_datetime: function(which, value) {
+ var parts = value ? value.split(' ') : ['', ''],
+ date = parts[0],
+ time = parts[1];
+ $('form#add-unit input[name=' + which + '_date]').val(date);
+ $('form#add-unit input[name=' + which + '_time]').val(time);
+ },
- schedule_options: function(nodes) {
- return nodes.map(function(node) {
- return $(''
+ ].join('')
+ };
/**
* Overrides Annotator._setupViewer to add a "click" event on viewer and to
* improve line breaks.
**/
- Annotator.prototype._setupViewer = function () {
- var self = this;
- this.viewer = new Annotator.Viewer({readOnly: this.options.readOnly});
- this.viewer.element.on('click', _.bind(this.onNoteClick, this));
- this.viewer.hide()
- .on("edit", this.onEditAnnotation)
- .on("delete", this.onDeleteAnnotation)
+ Annotator.prototype._setupViewer = function() {
+ var self = this;
+ this.viewer = new Annotator.Viewer({readOnly: this.options.readOnly});
+ this.viewer.element.on('click', _.bind(this.onNoteClick, this));
+ this.viewer.hide()
+ .on('edit', this.onEditAnnotation)
+ .on('delete', this.onDeleteAnnotation)
.addField({
- load: function (field, annotation) {
+ load: function(field, annotation) {
if (annotation.text) {
$(field).html(Utils.nl2br(Annotator.Util.escape(annotation.text)));
} else {
@@ -167,35 +167,35 @@ define([
}
})
.element.appendTo(this.wrapper).bind({
- "mouseover": this.clearViewerHideTimer,
- "mouseout": this.startViewerHideTimer
+ 'mouseover': this.clearViewerHideTimer,
+ 'mouseout': this.startViewerHideTimer
});
- return this;
- };
+ return this;
+ };
- Annotator.Editor.prototype.isShown = Annotator.Viewer.prototype.isShown;
+ Annotator.Editor.prototype.isShown = Annotator.Viewer.prototype.isShown;
/**
* Modifies Annotator.Editor.html template to add tabindex = -1 to
* form.annotator-widget and reverse order of Save and Cancel buttons.
**/
- Annotator.Editor.prototype.html = [
- '',
+ Annotator.Editor.prototype.html = [
+ '
',
'
',
- '
'
- ].join('');
+ '
'
+ ].join('');
/**
@@ -204,14 +204,14 @@ define([
*
* Also add a sr label for note textarea.
**/
- Annotator.Editor.prototype.show = _.compose(
- function (event) {
+ Annotator.Editor.prototype.show = _.compose(
+ function(event) {
// Add screen reader label for the note area. Note that the id of the tags element will not always be "0".
// It depends on the number of annotatable components on the page.
- var noteField = $("li.annotator-item >textarea", this.element).attr('id');
- if ($("label.sr[for='"+ noteField + "']", this.element).length === 0) {
- $('').insertBefore(
- $('#'+noteField, this.element)
+ var noteField = $('li.annotator-item >textarea', this.element).attr('id');
+ if ($("label.sr[for='" + noteField + "']", this.element).length === 0) {
+ $('').insertBefore(
+ $('#' + noteField, this.element)
);
}
@@ -228,15 +228,15 @@ define([
* which hides the viewer on ESC and saves on ENTER. We will define different
* behaviors for these in /plugins/accessibility.js
**/
- delete Annotator.Editor.prototype.events["textarea keydown"];
+ delete Annotator.Editor.prototype.events['textarea keydown'];
/**
* Modifies Annotator.onHighlightMouseover to avoid showing the viewer if the
* editor is opened.
**/
- Annotator.prototype.onHighlightMouseover = _.wrap(
+ Annotator.prototype.onHighlightMouseover = _.wrap(
Annotator.prototype.onHighlightMouseover,
- function (func, event) {
+ function(func, event) {
// Do nothing if the editor is opened.
if (this.editor.isShown()) {
return false;
@@ -249,84 +249,84 @@ define([
/**
* Modifies Annotator._setupWrapper to add a "click" event on '.annotator-hl'.
**/
- Annotator.prototype._setupWrapper = _.compose(
- function () {
+ Annotator.prototype._setupWrapper = _.compose(
+ function() {
this.element.on('click', '.annotator-hl', _.bind(this.onHighlightClick, this));
return this;
},
Annotator.prototype._setupWrapper
);
- $.extend(true, Annotator.prototype, {
- isFrozen: false,
- uid: _.uniqueId(),
+ $.extend(true, Annotator.prototype, {
+ isFrozen: false,
+ uid: _.uniqueId(),
- onHighlightClick: function (event) {
- event.stopPropagation();
- if (!this.editor.isShown()) {
- this.unfreezeAll();
- this.onHighlightMouseover.call(this, event);
- Annotator.frozenSrc = this;
- this.freezeAll();
- }
- },
+ onHighlightClick: function(event) {
+ event.stopPropagation();
+ if (!this.editor.isShown()) {
+ this.unfreezeAll();
+ this.onHighlightMouseover.call(this, event);
+ Annotator.frozenSrc = this;
+ this.freezeAll();
+ }
+ },
- onNoteClick: function (event) {
- var target = $(event.target);
- event.stopPropagation();
- Annotator.Util.preventEventDefault(event);
+ onNoteClick: function(event) {
+ var target = $(event.target);
+ event.stopPropagation();
+ Annotator.Util.preventEventDefault(event);
- if (!(target.is('.annotator-delete') || target.is('.annotator-close'))) {
- Annotator.frozenSrc = this;
- this.freezeAll();
- } else if (target.is('.annotator-close')) {
- this.viewer.hide();
- }
- },
+ if (!(target.is('.annotator-delete') || target.is('.annotator-close'))) {
+ Annotator.frozenSrc = this;
+ this.freezeAll();
+ } else if (target.is('.annotator-close')) {
+ this.viewer.hide();
+ }
+ },
- freeze: function () {
- if (!this.isFrozen) {
+ freeze: function() {
+ if (!this.isFrozen) {
// Remove default events
- this.removeEvents();
- this.viewer.element.unbind('mouseover mouseout');
- this.uid = _.uniqueId();
- $(document).on('click.edxnotes:freeze' + this.uid, _.bind(this.unfreeze, this));
- this.isFrozen = true;
- }
- return this;
- },
+ this.removeEvents();
+ this.viewer.element.unbind('mouseover mouseout');
+ this.uid = _.uniqueId();
+ $(document).on('click.edxnotes:freeze' + this.uid, _.bind(this.unfreeze, this));
+ this.isFrozen = true;
+ }
+ return this;
+ },
- unfreeze: function () {
- if (this.isFrozen) {
+ unfreeze: function() {
+ if (this.isFrozen) {
// Add default events
- this.addEvents();
- this.viewer.element.bind({
- 'mouseover': this.clearViewerHideTimer,
- 'mouseout': this.startViewerHideTimer
- });
- this.viewer.hide();
- $(document).off('click.edxnotes:freeze' + this.uid);
- this.isFrozen = false;
- Annotator.frozenSrc = null;
+ this.addEvents();
+ this.viewer.element.bind({
+ 'mouseover': this.clearViewerHideTimer,
+ 'mouseout': this.startViewerHideTimer
+ });
+ this.viewer.hide();
+ $(document).off('click.edxnotes:freeze' + this.uid);
+ this.isFrozen = false;
+ Annotator.frozenSrc = null;
+ }
+ return this;
+ },
+
+ freezeAll: function() {
+ _.invoke(Annotator._instances, 'freeze');
+ return this;
+ },
+
+ unfreezeAll: function() {
+ _.invoke(Annotator._instances, 'unfreeze');
+ return this;
+ },
+
+ showFrozenViewer: function(annotations, location) {
+ this.showViewer(annotations, location);
+ this.freezeAll();
+ return this;
}
- return this;
- },
-
- freezeAll: function () {
- _.invoke(Annotator._instances, 'freeze');
- return this;
- },
-
- unfreezeAll: function () {
- _.invoke(Annotator._instances, 'unfreeze');
- return this;
- },
-
- showFrozenViewer: function (annotations, location) {
- this.showViewer(annotations, location);
- this.freezeAll();
- return this;
- }
+ });
});
-});
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/tab_item.js b/lms/static/js/edxnotes/views/tab_item.js
index a07e228e1c..f315af5551 100644
--- a/lms/static/js/edxnotes/views/tab_item.js
+++ b/lms/static/js/edxnotes/views/tab_item.js
@@ -1,7 +1,7 @@
-;(function (define, undefined) {
-'use strict';
-define(['gettext', 'underscore', 'jquery', 'backbone', 'js/edxnotes/utils/template'],
-function (gettext, _, $, Backbone, templateUtils) {
+(function(define, undefined) {
+ 'use strict';
+ define(['gettext', 'underscore', 'jquery', 'backbone', 'js/edxnotes/utils/template'],
+function(gettext, _, $, Backbone, templateUtils) {
var TabItemView = Backbone.View.extend({
tagName: 'li',
className: 'tab',
@@ -9,15 +9,15 @@ function (gettext, _, $, Backbone, templateUtils) {
events: {
'click': 'selectHandler',
- 'click a': function (event) { event.preventDefault(); },
+ 'click a': function(event) { event.preventDefault(); },
'click .action-close': 'closeHandler'
},
- initialize: function (options) {
+ initialize: function(options) {
this.template = templateUtils.loadTemplate('tab-item');
this.$el.attr('id', this.model.get('identifier'));
this.listenTo(this.model, {
- 'change:is_active': function (model, value) {
+ 'change:is_active': function(model, value) {
this.$el.toggleClass(this.activeClassName, value);
if (value) {
this.$('.tab-label').prepend($('', {
@@ -32,20 +32,20 @@ function (gettext, _, $, Backbone, templateUtils) {
});
},
- render: function () {
+ render: function() {
var html = this.template(this.model.toJSON());
this.$el.html(html);
return this;
},
- selectHandler: function (event) {
+ selectHandler: function(event) {
event.preventDefault();
if (!this.model.isActive()) {
this.model.activate();
}
},
- closeHandler: function (event) {
+ closeHandler: function(event) {
event.preventDefault();
event.stopPropagation();
this.model.destroy();
diff --git a/lms/static/js/edxnotes/views/tab_panel.js b/lms/static/js/edxnotes/views/tab_panel.js
index 3f5d6d030d..811da93531 100644
--- a/lms/static/js/edxnotes/views/tab_panel.js
+++ b/lms/static/js/edxnotes/views/tab_panel.js
@@ -1,8 +1,8 @@
-;(function (define, undefined) {
-'use strict';
-define(['gettext', 'underscore', 'backbone', 'js/edxnotes/views/note_item',
+(function(define, undefined) {
+ 'use strict';
+ define(['gettext', 'underscore', 'backbone', 'js/edxnotes/views/note_item',
'common/js/components/views/paging_header', 'common/js/components/views/paging_footer'],
-function (gettext, _, Backbone, NoteItemView, PagingHeaderView, PagingFooterView) {
+function(gettext, _, Backbone, NoteItemView, PagingHeaderView, PagingFooterView) {
var TabPanelView = Backbone.View.extend({
tagName: 'section',
className: 'tab-panel',
@@ -12,7 +12,7 @@ function (gettext, _, Backbone, NoteItemView, PagingHeaderView, PagingFooterView
'tabindex': -1
},
- initialize: function (options) {
+ initialize: function(options) {
this.children = [];
this.options = _.extend({}, options);
if (this.options.createHeaderFooter) {
@@ -24,7 +24,7 @@ function (gettext, _, Backbone, NoteItemView, PagingHeaderView, PagingFooterView
}
},
- render: function () {
+ render: function() {
this.$el.html(this.getTitle());
this.renderView(this.pagingHeaderView);
this.renderContent();
@@ -39,13 +39,13 @@ function (gettext, _, Backbone, NoteItemView, PagingHeaderView, PagingFooterView
}
},
- renderContent: function () {
+ renderContent: function() {
return this;
},
- getNotes: function (collection) {
+ getNotes: function(collection) {
var container = document.createDocumentFragment(), scrollToTag = this.options.scrollToTag, view = this.title,
- notes = _.map(collection, function (model) {
+ notes = _.map(collection, function(model) {
var note = new NoteItemView({model: model, scrollToTag: scrollToTag, view: view});
container.appendChild(note.render().el);
return note;
@@ -55,11 +55,11 @@ function (gettext, _, Backbone, NoteItemView, PagingHeaderView, PagingFooterView
return container;
},
- getTitle: function () {
+ getTitle: function() {
return this.title ? this.titleTemplate({text: gettext(this.title)}) : '';
},
- remove: function () {
+ remove: function() {
_.invoke(this.children, 'remove');
this.children = null;
Backbone.View.prototype.remove.call(this);
diff --git a/lms/static/js/edxnotes/views/tab_view.js b/lms/static/js/edxnotes/views/tab_view.js
index c73ce042fc..94dfe20704 100644
--- a/lms/static/js/edxnotes/views/tab_view.js
+++ b/lms/static/js/edxnotes/views/tab_view.js
@@ -1,150 +1,150 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/html-utils',
- 'js/edxnotes/models/tab'
-], function ($, _, Backbone, HtmlUtils, TabModel) {
- var TabView = Backbone.View.extend({
- PanelConstructor: null,
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/html-utils',
+ 'js/edxnotes/models/tab'
+ ], function($, _, Backbone, HtmlUtils, TabModel) {
+ var TabView = Backbone.View.extend({
+ PanelConstructor: null,
- tabInfo: {
- name: '',
- class_name: ''
- },
+ tabInfo: {
+ name: '',
+ class_name: ''
+ },
- initialize: function (options) {
- _.bindAll(this, 'showLoadingIndicator', 'hideLoadingIndicator');
- this.options = _.defaults(options || {}, {
- createTabOnInitialization: true,
- createHeaderFooter: true
- });
+ initialize: function(options) {
+ _.bindAll(this, 'showLoadingIndicator', 'hideLoadingIndicator');
+ this.options = _.defaults(options || {}, {
+ createTabOnInitialization: true,
+ createHeaderFooter: true
+ });
- if (this.options.createTabOnInitialization) {
- this.createTab();
- }
- },
+ if (this.options.createTabOnInitialization) {
+ this.createTab();
+ }
+ },
/**
* Creates a tab for the view.
*/
- createTab: function () {
- this.tabModel = new TabModel(this.tabInfo);
- this.options.tabsCollection.add(this.tabModel);
- this.listenTo(this.tabModel, {
- 'change:is_active': function (model, value) {
- if (value) {
- this.render();
- } else {
+ createTab: function() {
+ this.tabModel = new TabModel(this.tabInfo);
+ this.options.tabsCollection.add(this.tabModel);
+ this.listenTo(this.tabModel, {
+ 'change:is_active': function(model, value) {
+ if (value) {
+ this.render();
+ } else {
+ this.destroySubView();
+ }
+ },
+ 'destroy': function() {
this.destroySubView();
+ this.tabModel = null;
+ this.onClose();
}
- },
- 'destroy': function () {
- this.destroySubView();
- this.tabModel = null;
- this.onClose();
- }
- });
- },
+ });
+ },
/**
* Renders content for the view.
*/
- render: function () {
- this.hideErrorMessage().showLoadingIndicator();
+ render: function() {
+ this.hideErrorMessage().showLoadingIndicator();
// If the view is already rendered, destroy it.
- this.destroySubView();
- this.renderContent().always(this.hideLoadingIndicator);
- this.$('.sr-is-focusable.sr-tab-panel').focus();
- return this;
- },
+ this.destroySubView();
+ this.renderContent().always(this.hideLoadingIndicator);
+ this.$('.sr-is-focusable.sr-tab-panel').focus();
+ return this;
+ },
- renderContent: function () {
- this.contentView = this.getSubView();
- this.$('.wrapper-tabs').append(this.contentView.render().$el);
- return $.Deferred().resolve().promise();
- },
+ renderContent: function() {
+ this.contentView = this.getSubView();
+ this.$('.wrapper-tabs').append(this.contentView.render().$el);
+ return $.Deferred().resolve().promise();
+ },
- getSubView: function () {
- var collection = this.getCollection();
- return new this.PanelConstructor(
- {
- collection: collection,
- scrollToTag: this.options.scrollToTag,
- createHeaderFooter: this.options.createHeaderFooter
- }
+ getSubView: function() {
+ var collection = this.getCollection();
+ return new this.PanelConstructor(
+ {
+ collection: collection,
+ scrollToTag: this.options.scrollToTag,
+ createHeaderFooter: this.options.createHeaderFooter
+ }
);
- },
+ },
- destroySubView: function () {
- if (this.contentView) {
- this.contentView.remove();
- this.contentView = null;
- }
- },
+ destroySubView: function() {
+ if (this.contentView) {
+ this.contentView.remove();
+ this.contentView = null;
+ }
+ },
/**
* Returns collection for the view.
* @return {Backbone.Collection}
*/
- getCollection: function () {
- return this.collection;
- },
+ getCollection: function() {
+ return this.collection;
+ },
/**
* Callback that is called on closing the tab.
*/
- onClose: function () { },
+ onClose: function() { },
/**
* Returns the page's loading indicator.
*/
- getLoadingIndicator: function() {
- return this.$('.ui-loading');
- },
+ getLoadingIndicator: function() {
+ return this.$('.ui-loading');
+ },
/**
* Shows the page's loading indicator.
*/
- showLoadingIndicator: function() {
- this.getLoadingIndicator().removeClass('is-hidden');
- return this;
- },
+ showLoadingIndicator: function() {
+ this.getLoadingIndicator().removeClass('is-hidden');
+ return this;
+ },
/**
* Hides the page's loading indicator.
*/
- hideLoadingIndicator: function() {
- this.getLoadingIndicator().addClass('is-hidden');
- return this;
- },
+ hideLoadingIndicator: function() {
+ this.getLoadingIndicator().addClass('is-hidden');
+ return this;
+ },
/**
* Shows error message.
*/
- showErrorMessageHtml: function (htmlMessage) {
- var $wrapper = this.$('.wrapper-msg');
- $wrapper.removeClass('is-hidden');
+ showErrorMessageHtml: function(htmlMessage) {
+ var $wrapper = this.$('.wrapper-msg');
+ $wrapper.removeClass('is-hidden');
- HtmlUtils.setHtml($wrapper.find('.msg-content .copy'), htmlMessage);
- return this;
- },
+ HtmlUtils.setHtml($wrapper.find('.msg-content .copy'), htmlMessage);
+ return this;
+ },
/**
* Hides error message.
*/
- hideErrorMessage: function () {
- this.$('.wrapper-msg')
+ hideErrorMessage: function() {
+ this.$('.wrapper-msg')
.addClass('is-hidden')
.find('.msg-content .copy').html('');
- return this;
- }
- });
+ return this;
+ }
+ });
- return TabView;
-});
+ return TabView;
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/tabs/course_structure.js b/lms/static/js/edxnotes/views/tabs/course_structure.js
index 6d088dba96..e26f30fcf7 100644
--- a/lms/static/js/edxnotes/views/tabs/course_structure.js
+++ b/lms/static/js/edxnotes/views/tabs/course_structure.js
@@ -1,58 +1,58 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'gettext', 'underscore', 'js/edxnotes/views/note_group', 'js/edxnotes/views/tab_panel',
- 'js/edxnotes/views/tab_view'
-], function (gettext, _, NoteGroupView, TabPanelView, TabView) {
- var view = "Location in Course";
- var CourseStructureView = TabView.extend({
- PanelConstructor: TabPanelView.extend({
- id: 'structure-panel',
- title: view,
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'gettext', 'underscore', 'js/edxnotes/views/note_group', 'js/edxnotes/views/tab_panel',
+ 'js/edxnotes/views/tab_view'
+ ], function(gettext, _, NoteGroupView, TabPanelView, TabView) {
+ var view = 'Location in Course';
+ var CourseStructureView = TabView.extend({
+ PanelConstructor: TabPanelView.extend({
+ id: 'structure-panel',
+ title: view,
- renderContent: function () {
- var courseStructure = this.collection.getCourseStructure(),
- container = document.createDocumentFragment();
+ renderContent: function() {
+ var courseStructure = this.collection.getCourseStructure(),
+ container = document.createDocumentFragment();
- _.each(courseStructure.chapters, function (chapterInfo) {
- var chapterView = this.getChapterGroupView(chapterInfo);
- _.each(chapterInfo.children, function (location) {
- var sectionInfo = courseStructure.sections[location],
- sectionView;
- if (sectionInfo) {
- sectionView = chapterView.addChild(sectionInfo);
- _.each(sectionInfo.children, function (location) {
- var notes = courseStructure.units[location];
- if (notes) {
- sectionView.addChild(this.getNotes(notes));
- }
- }, this);
- }
+ _.each(courseStructure.chapters, function(chapterInfo) {
+ var chapterView = this.getChapterGroupView(chapterInfo);
+ _.each(chapterInfo.children, function(location) {
+ var sectionInfo = courseStructure.sections[location],
+ sectionView;
+ if (sectionInfo) {
+ sectionView = chapterView.addChild(sectionInfo);
+ _.each(sectionInfo.children, function(location) {
+ var notes = courseStructure.units[location];
+ if (notes) {
+ sectionView.addChild(this.getNotes(notes));
+ }
+ }, this);
+ }
+ }, this);
+ container.appendChild(chapterView.render().el);
}, this);
- container.appendChild(chapterView.render().el);
- }, this);
- this.$el.append(container);
- return this;
- },
+ this.$el.append(container);
+ return this;
+ },
- getChapterGroupView: function (chapter, section) {
- var group = new NoteGroupView.ChapterView({
- chapter: chapter,
- section: section
- });
- this.children.push(group);
- return group;
+ getChapterGroupView: function(chapter, section) {
+ var group = new NoteGroupView.ChapterView({
+ chapter: chapter,
+ section: section
+ });
+ this.children.push(group);
+ return group;
+ }
+ }),
+
+ tabInfo: {
+ name: gettext('Location in Course'),
+ identifier: 'view-course-structure',
+ icon: 'fa fa-list-ul',
+ view: view
}
- }),
+ });
- tabInfo: {
- name: gettext('Location in Course'),
- identifier: 'view-course-structure',
- icon: 'fa fa-list-ul',
- view: view
- }
+ return CourseStructureView;
});
-
- return CourseStructureView;
-});
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/tabs/recent_activity.js b/lms/static/js/edxnotes/views/tabs/recent_activity.js
index e657b4311d..a82827f711 100644
--- a/lms/static/js/edxnotes/views/tabs/recent_activity.js
+++ b/lms/static/js/edxnotes/views/tabs/recent_activity.js
@@ -1,33 +1,33 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'gettext', 'js/edxnotes/views/tab_panel', 'js/edxnotes/views/tab_view'
-], function (gettext, TabPanelView, TabView) {
- var view = 'Recent Activity';
- var RecentActivityView = TabView.extend({
- PanelConstructor: TabPanelView.extend({
- id: 'recent-panel',
- title: view,
- className: function () {
- return [
- TabPanelView.prototype.className,
- 'note-group'
- ].join(' ');
- },
- renderContent: function () {
- this.$el.append(this.getNotes(this.collection.toArray()));
- return this;
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'gettext', 'js/edxnotes/views/tab_panel', 'js/edxnotes/views/tab_view'
+ ], function(gettext, TabPanelView, TabView) {
+ var view = 'Recent Activity';
+ var RecentActivityView = TabView.extend({
+ PanelConstructor: TabPanelView.extend({
+ id: 'recent-panel',
+ title: view,
+ className: function() {
+ return [
+ TabPanelView.prototype.className,
+ 'note-group'
+ ].join(' ');
+ },
+ renderContent: function() {
+ this.$el.append(this.getNotes(this.collection.toArray()));
+ return this;
+ }
+ }),
+
+ tabInfo: {
+ identifier: 'view-recent-activity',
+ name: gettext('Recent Activity'),
+ icon: 'fa fa-clock-o',
+ view: view
}
- }),
+ });
- tabInfo: {
- identifier: 'view-recent-activity',
- name: gettext('Recent Activity'),
- icon: 'fa fa-clock-o',
- view: view
- }
+ return RecentActivityView;
});
-
- return RecentActivityView;
-});
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/tabs/search_results.js b/lms/static/js/edxnotes/views/tabs/search_results.js
index ade2dd78ce..b680047c79 100644
--- a/lms/static/js/edxnotes/views/tabs/search_results.js
+++ b/lms/static/js/edxnotes/views/tabs/search_results.js
@@ -1,154 +1,154 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'jquery', 'underscore', 'gettext', 'js/edxnotes/views/tab_panel', 'js/edxnotes/views/tab_view',
- 'js/edxnotes/views/search_box'
-], function ($, _, gettext, TabPanelView, TabView, SearchBoxView) {
- var view = 'Search Results';
- var SearchResultsView = TabView.extend({
- PanelConstructor: TabPanelView.extend({
- id: 'search-results-panel',
- title: view,
- className: function () {
- return [
- TabPanelView.prototype.className,
- 'note-group'
- ].join(' ');
- },
- renderContent: function () {
- this.$el.append(this.getNotes(this.collection.toArray()));
- return this;
- }
- }),
-
- NoResultsViewConstructor: TabPanelView.extend({
- id: 'no-results-panel',
- title: 'No results found',
- className: function () {
- return [
- TabPanelView.prototype.className,
- 'note-group'
- ].join(' ');
- },
- renderContent: function () {
- var message = gettext('No results found for "%(query_string)s". Please try searching again.');
-
- this.$el.append($('', {
- text: interpolate(message, {
- query_string: this.options.searchQuery
- }, true)
- }));
-
- return this;
- }
- }),
-
- tabInfo: {
- identifier: 'view-search-results',
- name: gettext('Search Results'),
- icon: 'fa fa-search',
- is_closable: true,
- view: view
- },
-
- initialize: function (options) {
- this.options = _.extend({}, options);
- _.bindAll(this, 'onBeforeSearchStart', 'onSearch', 'onSearchError');
- TabView.prototype.initialize.call(this, options);
- this.searchResults = null;
- this.searchBox = new SearchBoxView({
- el: document.getElementById('search-notes-form'),
- debug: this.options.debug,
- perPage: this.options.perPage,
- beforeSearchStart: this.onBeforeSearchStart,
- search: this.onSearch,
- error: this.onSearchError
- });
- },
-
- renderContent: function () {
- this.getLoadingIndicator().focus();
- return this.searchPromise.done(_.bind(function () {
- this.contentView = this.getSubView();
- if (this.contentView) {
- this.$('.wrapper-tabs').append(this.contentView.render().$el);
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'jquery', 'underscore', 'gettext', 'js/edxnotes/views/tab_panel', 'js/edxnotes/views/tab_view',
+ 'js/edxnotes/views/search_box'
+ ], function($, _, gettext, TabPanelView, TabView, SearchBoxView) {
+ var view = 'Search Results';
+ var SearchResultsView = TabView.extend({
+ PanelConstructor: TabPanelView.extend({
+ id: 'search-results-panel',
+ title: view,
+ className: function() {
+ return [
+ TabPanelView.prototype.className,
+ 'note-group'
+ ].join(' ');
+ },
+ renderContent: function() {
+ this.$el.append(this.getNotes(this.collection.toArray()));
+ return this;
}
- }, this));
- },
+ }),
- getSubView: function () {
- var collection = this.getCollection();
- if (collection) {
- if (collection.length) {
- return new this.PanelConstructor({
- collection: collection,
- searchQuery: this.searchResults.searchQuery,
- scrollToTag: this.options.scrollToTag,
- createHeaderFooter: this.options.createHeaderFooter
- });
- } else {
- return new this.NoResultsViewConstructor({
- searchQuery: this.searchResults.searchQuery
- });
+ NoResultsViewConstructor: TabPanelView.extend({
+ id: 'no-results-panel',
+ title: 'No results found',
+ className: function() {
+ return [
+ TabPanelView.prototype.className,
+ 'note-group'
+ ].join(' ');
+ },
+ renderContent: function() {
+ var message = gettext('No results found for "%(query_string)s". Please try searching again.');
+
+ this.$el.append($('', {
+ text: interpolate(message, {
+ query_string: this.options.searchQuery
+ }, true)
+ }));
+
+ return this;
}
- }
+ }),
- return null;
- },
+ tabInfo: {
+ identifier: 'view-search-results',
+ name: gettext('Search Results'),
+ icon: 'fa fa-search',
+ is_closable: true,
+ view: view
+ },
- getCollection: function () {
- if (this.searchResults) {
- return this.searchResults.collection;
- }
+ initialize: function(options) {
+ this.options = _.extend({}, options);
+ _.bindAll(this, 'onBeforeSearchStart', 'onSearch', 'onSearchError');
+ TabView.prototype.initialize.call(this, options);
+ this.searchResults = null;
+ this.searchBox = new SearchBoxView({
+ el: document.getElementById('search-notes-form'),
+ debug: this.options.debug,
+ perPage: this.options.perPage,
+ beforeSearchStart: this.onBeforeSearchStart,
+ search: this.onSearch,
+ error: this.onSearchError
+ });
+ },
- return null;
- },
+ renderContent: function() {
+ this.getLoadingIndicator().focus();
+ return this.searchPromise.done(_.bind(function() {
+ this.contentView = this.getSubView();
+ if (this.contentView) {
+ this.$('.wrapper-tabs').append(this.contentView.render().$el);
+ }
+ }, this));
+ },
- onClose: function () {
- this.searchResults = null;
- this.searchBox.clearInput();
- },
+ getSubView: function() {
+ var collection = this.getCollection();
+ if (collection) {
+ if (collection.length) {
+ return new this.PanelConstructor({
+ collection: collection,
+ searchQuery: this.searchResults.searchQuery,
+ scrollToTag: this.options.scrollToTag,
+ createHeaderFooter: this.options.createHeaderFooter
+ });
+ } else {
+ return new this.NoResultsViewConstructor({
+ searchQuery: this.searchResults.searchQuery
+ });
+ }
+ }
- onBeforeSearchStart: function () {
- this.searchDeferred = $.Deferred();
- this.searchPromise = this.searchDeferred.promise();
- this.hideErrorMessage();
- this.searchResults = null;
+ return null;
+ },
+
+ getCollection: function() {
+ if (this.searchResults) {
+ return this.searchResults.collection;
+ }
+
+ return null;
+ },
+
+ onClose: function() {
+ this.searchResults = null;
+ this.searchBox.clearInput();
+ },
+
+ onBeforeSearchStart: function() {
+ this.searchDeferred = $.Deferred();
+ this.searchPromise = this.searchDeferred.promise();
+ this.hideErrorMessage();
+ this.searchResults = null;
// If tab doesn't exist, creates it.
- if (!this.tabModel) {
- this.createTab();
- }
+ if (!this.tabModel) {
+ this.createTab();
+ }
// If tab is not already active, makes it active
- if (!this.tabModel.isActive()) {
- this.tabModel.activate();
- } else {
- this.render();
- }
- },
+ if (!this.tabModel.isActive()) {
+ this.tabModel.activate();
+ } else {
+ this.render();
+ }
+ },
- onSearch: function (collection, searchQuery) {
- this.searchResults = {
- collection: collection,
- searchQuery: searchQuery
- };
+ onSearch: function(collection, searchQuery) {
+ this.searchResults = {
+ collection: collection,
+ searchQuery: searchQuery
+ };
- if (this.searchDeferred) {
- this.searchDeferred.resolve();
- }
+ if (this.searchDeferred) {
+ this.searchDeferred.resolve();
+ }
- if (this.contentView) {
- this.contentView.$el.focus();
- }
- },
+ if (this.contentView) {
+ this.contentView.$el.focus();
+ }
+ },
- onSearchError: function (errorMessage) {
- this.showErrorMessageHtml(errorMessage);
- if (this.searchDeferred) {
- this.searchDeferred.reject();
+ onSearchError: function(errorMessage) {
+ this.showErrorMessageHtml(errorMessage);
+ if (this.searchDeferred) {
+ this.searchDeferred.reject();
+ }
}
- }
+ });
+
+ return SearchResultsView;
});
-
- return SearchResultsView;
-});
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/tabs/tags.js b/lms/static/js/edxnotes/views/tabs/tags.js
index fb3dab6565..0c029039f9 100644
--- a/lms/static/js/edxnotes/views/tabs/tags.js
+++ b/lms/static/js/edxnotes/views/tabs/tags.js
@@ -1,82 +1,82 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'gettext', 'jquery', 'underscore', 'js/edxnotes/views/note_group', 'js/edxnotes/views/tab_panel',
- 'js/edxnotes/views/tab_view'
-], function (gettext, $, _, NoteGroupView, TabPanelView, TabView) {
- var view = 'Tags';
- var TagsView = TabView.extend({
- scrollToTag: function(tagName) {
- var titleElement, displayedTitle;
- if (!this.tabModel.isActive()) {
- this.tabModel.activate();
- }
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'gettext', 'jquery', 'underscore', 'js/edxnotes/views/note_group', 'js/edxnotes/views/tab_panel',
+ 'js/edxnotes/views/tab_view'
+ ], function(gettext, $, _, NoteGroupView, TabPanelView, TabView) {
+ var view = 'Tags';
+ var TagsView = TabView.extend({
+ scrollToTag: function(tagName) {
+ var titleElement, displayedTitle;
+ if (!this.tabModel.isActive()) {
+ this.tabModel.activate();
+ }
- displayedTitle = this.contentView.titleMap[tagName.toLowerCase()];
- titleElement = this.$el.find('.tags-title').filter(
- function(){ return $(this).text() === displayedTitle; }
+ displayedTitle = this.contentView.titleMap[tagName.toLowerCase()];
+ titleElement = this.$el.find('.tags-title').filter(
+ function() { return $(this).text() === displayedTitle; }
);
- $('html,body').animate(
- { scrollTop: titleElement.offset().top - 10 },
+ $('html,body').animate(
+ {scrollTop: titleElement.offset().top - 10},
'slow',
- function () { titleElement.focus(); }
+ function() { titleElement.focus(); }
);
- },
+ },
- initialize: function (options) {
- this.options = _.extend({}, options);
- TabView.prototype.initialize.call(this, options);
- _.bindAll(this, 'scrollToTag');
- this.options.scrollToTag = this.scrollToTag;
- },
+ initialize: function(options) {
+ this.options = _.extend({}, options);
+ TabView.prototype.initialize.call(this, options);
+ _.bindAll(this, 'scrollToTag');
+ this.options.scrollToTag = this.scrollToTag;
+ },
- PanelConstructor: TabPanelView.extend({
- id: 'tags-panel',
- title: view,
+ PanelConstructor: TabPanelView.extend({
+ id: 'tags-panel',
+ title: view,
// Translators: this is a title shown before all Notes that have no associated tags. It is put within
// brackets to differentiate it from user-defined tags, but it should still be translated.
- noTags: gettext('[no tags]'), // User-defined tags cannot have spaces, so no risk of a collision.
+ noTags: gettext('[no tags]'), // User-defined tags cannot have spaces, so no risk of a collision.
- renderContent: function () {
- var notesByTag = {}, noTags = this.noTags, addNoteForTag, noteList, tags, i,
- sortedTagNames, container, group, noteGroup, tagTitle, titleMap;
+ renderContent: function() {
+ var notesByTag = {}, noTags = this.noTags, addNoteForTag, noteList, tags, i,
+ sortedTagNames, container, group, noteGroup, tagTitle, titleMap;
// Iterate through all the notes and build up a dictionary structure by tag.
// Note that the collection will be in most-recently updated order already.
- addNoteForTag = function (note, tag) {
- noteList = notesByTag[tag.toLowerCase()];
- if (noteList === undefined) {
- noteList = [];
- notesByTag[tag.toLowerCase()] = noteList;
- }
+ addNoteForTag = function(note, tag) {
+ noteList = notesByTag[tag.toLowerCase()];
+ if (noteList === undefined) {
+ noteList = [];
+ notesByTag[tag.toLowerCase()] = noteList;
+ }
// If a note was tagged with the same tag more than once, don't add again.
// We can assume it would be the last element of the list because we iterate through
// all tags on a given note before moving on to the text note.
- if (noteList.length === 0 || noteList[noteList.length - 1] !== note) {
- noteList.push(note);
- }
- };
-
- this.collection.each(function(note){
- tags = note.get('tags');
- if (tags.length === 0) {
- addNoteForTag(note, noTags);
- }
- else {
- for (i = 0; i < tags.length; i++) {
- addNoteForTag(note, tags[i]);
+ if (noteList.length === 0 || noteList[noteList.length - 1] !== note) {
+ noteList.push(note);
}
- }
- });
+ };
- sortedTagNames = Object.keys(notesByTag).sort(function (a, b) {
+ this.collection.each(function(note) {
+ tags = note.get('tags');
+ if (tags.length === 0) {
+ addNoteForTag(note, noTags);
+ }
+ else {
+ for (i = 0; i < tags.length; i++) {
+ addNoteForTag(note, tags[i]);
+ }
+ }
+ });
+
+ sortedTagNames = Object.keys(notesByTag).sort(function(a, b) {
// "no tags" should always appear last
- if (a === noTags) {
- return 1;
- }
- else if (b === noTags) {
- return -1;
- }
+ if (a === noTags) {
+ return 1;
+ }
+ else if (b === noTags) {
+ return -1;
+ }
else if (notesByTag[a].length > notesByTag[b].length) {
return -1;
}
@@ -86,54 +86,54 @@ define([
else {
return a.toLowerCase() <= b.toLowerCase() ? -1 : 1;
}
- });
+ });
- container = document.createDocumentFragment();
+ container = document.createDocumentFragment();
// Store map of titles for scrollToTag functionality.
- this.titleMap = {};
- titleMap = this.titleMap;
+ this.titleMap = {};
+ titleMap = this.titleMap;
- _.each(sortedTagNames, function (tagName) {
- noteGroup = notesByTag[tagName];
- var tagTitle = interpolate_text(
- "{tagName} ({numberOfNotesWithTag})",
+ _.each(sortedTagNames, function(tagName) {
+ noteGroup = notesByTag[tagName];
+ var tagTitle = interpolate_text(
+ '{tagName} ({numberOfNotesWithTag})',
{tagName: tagName, numberOfNotesWithTag: noteGroup.length}
);
- group = this.getGroup(tagTitle);
- titleMap[tagName] = tagTitle;
+ group = this.getGroup(tagTitle);
+ titleMap[tagName] = tagTitle;
- group.addChild(this.getNotes(noteGroup));
- container.appendChild(group.render().el);
- }, this);
+ group.addChild(this.getNotes(noteGroup));
+ container.appendChild(group.render().el);
+ }, this);
- this.$el.append(container);
- return this;
- },
+ this.$el.append(container);
+ return this;
+ },
- getGroup: function (tagName) {
- var group = new NoteGroupView.GroupView({
- displayName: tagName,
- template: '',
- className: "note-group"
- });
- this.children.push(group);
- return group;
- }
- }),
+ getGroup: function(tagName) {
+ var group = new NoteGroupView.GroupView({
+ displayName: tagName,
+ template: '',
+ className: 'note-group'
+ });
+ this.children.push(group);
+ return group;
+ }
+ }),
- tabInfo: {
+ tabInfo: {
// Translators: 'Tags' is the name of the view (noun) within the Student Notes page that shows all
// notes organized by the tags the student has associated with them (if any). When defining a
// note in the courseware, the student can choose to associate 1 or more tags with the note
// in order to group similar notes together and help with search.
- name: gettext('Tags'),
- identifier: 'view-tags',
- icon: 'fa fa-tag',
- view: view
- }
- });
+ name: gettext('Tags'),
+ identifier: 'view-tags',
+ icon: 'fa fa-tag',
+ view: view
+ }
+ });
- return TagsView;
-});
+ return TagsView;
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/tabs_list.js b/lms/static/js/edxnotes/views/tabs_list.js
index 52d246dfbe..0dff743de9 100644
--- a/lms/static/js/edxnotes/views/tabs_list.js
+++ b/lms/static/js/edxnotes/views/tabs_list.js
@@ -1,41 +1,41 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'underscore', 'backbone', 'js/edxnotes/views/tab_item'
-], function (_, Backbone, TabItemView) {
- var TabsListView = Backbone.View.extend({
- tagName: 'ul',
- className: 'tabs',
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'underscore', 'backbone', 'js/edxnotes/views/tab_item'
+ ], function(_, Backbone, TabItemView) {
+ var TabsListView = Backbone.View.extend({
+ tagName: 'ul',
+ className: 'tabs',
- initialize: function (options) {
- this.options = options;
- this.listenTo(this.collection, {
- 'add': this.createTab,
- 'destroy': function (model, collection) {
- if (model.isActive() && collection.length) {
- collection.at(0).activate();
+ initialize: function(options) {
+ this.options = options;
+ this.listenTo(this.collection, {
+ 'add': this.createTab,
+ 'destroy': function(model, collection) {
+ if (model.isActive() && collection.length) {
+ collection.at(0).activate();
+ }
}
+ });
+ },
+
+ render: function() {
+ this.collection.each(this.createTab, this);
+ if (this.collection.length) {
+ this.collection.at(0).activate();
}
- });
- },
+ return this;
+ },
- render: function () {
- this.collection.each(this.createTab, this);
- if (this.collection.length) {
- this.collection.at(0).activate();
+ createTab: function(model) {
+ var tab = new TabItemView({
+ model: model
+ });
+ tab.render().$el.appendTo(this.$el);
+ return tab;
}
- return this;
- },
+ });
- createTab: function (model) {
- var tab = new TabItemView({
- model: model
- });
- tab.render().$el.appendTo(this.$el);
- return tab;
- }
+ return TabsListView;
});
-
- return TabsListView;
-});
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/edxnotes/views/visibility_decorator.js b/lms/static/js/edxnotes/views/visibility_decorator.js
index 6436613f28..7d59e2d3f6 100644
--- a/lms/static/js/edxnotes/views/visibility_decorator.js
+++ b/lms/static/js/edxnotes/views/visibility_decorator.js
@@ -1,29 +1,29 @@
-;(function (define, undefined) {
-'use strict';
-define([
- 'jquery', 'underscore', 'js/edxnotes/views/notes_factory'
-], function($, _, NotesFactory) {
- var parameters = {}, visibility = null,
- getIds, createNote, cleanup, factory;
+(function(define, undefined) {
+ 'use strict';
+ define([
+ 'jquery', 'underscore', 'js/edxnotes/views/notes_factory'
+ ], function($, _, NotesFactory) {
+ var parameters = {}, visibility = null,
+ getIds, createNote, cleanup, factory;
- getIds = function () {
- return _.map($('.edx-notes-wrapper'), function (element) {
+ getIds = function() {
+ return _.map($('.edx-notes-wrapper'), function(element) {
return element.id;
});
};
- createNote = function (element, params) {
+ createNote = function(element, params) {
if (params) {
return NotesFactory.factory(element, params);
}
return null;
};
- cleanup = function (ids) {
+ cleanup = function(ids) {
var list = _.clone(Annotator._instances);
ids = ids || [];
- _.each(list, function (instance) {
+ _.each(list, function(instance) {
var id = instance.element.attr('id');
if (!_.contains(ids, id)) {
instance.destroy();
@@ -31,7 +31,7 @@ define([
});
};
- factory = function (element, params, isVisible) {
+ factory = function(element, params, isVisible) {
// When switching sequentials, we need to keep track of the
// parameters of each element and the visibility (that may have been
// changed by the checkbox).
@@ -53,22 +53,22 @@ define([
return null;
};
- return {
- factory: factory,
+ return {
+ factory: factory,
- enableNote: function (element) {
- createNote(element, parameters[element.id]);
- visibility = true;
- },
+ enableNote: function(element) {
+ createNote(element, parameters[element.id]);
+ visibility = true;
+ },
- disableNotes: function () {
- cleanup();
- visibility = false;
- },
+ disableNotes: function() {
+ cleanup();
+ visibility = false;
+ },
- _setVisibility: function (state) {
- visibility = state;
- },
- }
-});
+ _setVisibility: function(state) {
+ visibility = state;
+ }
+ };
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/financial-assistance/financial_assistance_form_factory.js b/lms/static/js/financial-assistance/financial_assistance_form_factory.js
index 0cc77a7617..d407b67208 100644
--- a/lms/static/js/financial-assistance/financial_assistance_form_factory.js
+++ b/lms/static/js/financial-assistance/financial_assistance_form_factory.js
@@ -1,11 +1,11 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'js/financial-assistance/views/financial_assistance_form_view'
],
- function (FinancialAssistanceFormView) {
- return function (options) {
+ function(FinancialAssistanceFormView) {
+ return function(options) {
var formView = new FinancialAssistanceFormView({
el: '.financial-assistance-wrapper',
context: options
diff --git a/lms/static/js/financial-assistance/models/financial_assistance_model.js b/lms/static/js/financial-assistance/models/financial_assistance_model.js
index 3039059158..b324cbcbfc 100644
--- a/lms/static/js/financial-assistance/models/financial_assistance_model.js
+++ b/lms/static/js/financial-assistance/models/financial_assistance_model.js
@@ -1,9 +1,9 @@
/**
* Model for Financial Assistance.
*/
-(function (define) {
+(function(define) {
'use strict';
- define(['backbone'], function (Backbone) {
+ define(['backbone'], function(Backbone) {
var FinancialAssistance = Backbone.Model.extend({
initialize: function(options) {
this.url = options.url;
diff --git a/lms/static/js/financial-assistance/views/financial_assistance_form_view.js b/lms/static/js/financial-assistance/views/financial_assistance_form_view.js
index d077076e8d..7b03e112f8 100644
--- a/lms/static/js/financial-assistance/views/financial_assistance_form_view.js
+++ b/lms/static/js/financial-assistance/views/financial_assistance_form_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -23,129 +23,129 @@
successTpl,
formFieldTpl
) {
- return FormView.extend({
- el: '.financial-assistance-wrapper',
- events: {
- 'click .js-submit-form': 'submitForm'
- },
- tpl: formViewTpl,
- fieldTpl: formFieldTpl,
- formType: 'financial-assistance',
- requiredStr: '',
- submitButton: '.js-submit-form',
+ return FormView.extend({
+ el: '.financial-assistance-wrapper',
+ events: {
+ 'click .js-submit-form': 'submitForm'
+ },
+ tpl: formViewTpl,
+ fieldTpl: formFieldTpl,
+ formType: 'financial-assistance',
+ requiredStr: '',
+ submitButton: '.js-submit-form',
- initialize: function(data) {
- var context = data.context,
- fields = context.fields;
+ initialize: function(data) {
+ var context = data.context,
+ fields = context.fields;
// Add default option to course array
- this.addDefaultOption(fields, 0);
+ this.addDefaultOption(fields, 0);
// Add default option to household income array
- this.addDefaultOption(fields, 1);
+ this.addDefaultOption(fields, 1);
// Set non-form data needed to render the View
- this.context = {
- dashboard_url: context.dashboard_url,
- header_text: context.header_text,
- platform_name: context.platform_name,
- student_faq_url: context.student_faq_url,
- account_settings_url: context.account_settings_url
- };
+ this.context = {
+ dashboard_url: context.dashboard_url,
+ header_text: context.header_text,
+ platform_name: context.platform_name,
+ student_faq_url: context.student_faq_url,
+ account_settings_url: context.account_settings_url
+ };
// Make the value accessible to this View
- this.user_details = context.user_details;
+ this.user_details = context.user_details;
// Initialize the model and set user details
- this.model = new FinancialAssistanceModel({
- url: context.submit_url
- });
- this.model.set( context.user_details );
- this.listenTo( this.model, 'error', this.saveError );
- this.model.on('sync', this.renderSuccess, this);
+ this.model = new FinancialAssistanceModel({
+ url: context.submit_url
+ });
+ this.model.set(context.user_details);
+ this.listenTo(this.model, 'error', this.saveError);
+ this.model.on('sync', this.renderSuccess, this);
// Build the form
- this.buildForm( fields );
- },
+ this.buildForm(fields);
+ },
- render: function(html) {
- var data = _.extend( this.model.toJSON(), this.context, {
- fields: html || '',
- });
+ render: function(html) {
+ var data = _.extend(this.model.toJSON(), this.context, {
+ fields: html || ''
+ });
- this.$el.html(_.template(this.tpl)(data));
+ this.$el.html(_.template(this.tpl)(data));
- this.postRender();
- this.validateCountry();
+ this.postRender();
+ this.validateCountry();
- return this;
- },
+ return this;
+ },
- renderSuccess: function() {
- this.$el.html(_.template(successTpl)({
- course: this.model.get('course'),
- dashboard_url: this.context.dashboard_url
- }));
+ renderSuccess: function() {
+ this.$el.html(_.template(successTpl)({
+ course: this.model.get('course'),
+ dashboard_url: this.context.dashboard_url
+ }));
- $('.js-success-message').focus();
- },
+ $('.js-success-message').focus();
+ },
- saveError: function(error) {
- /*jslint maxlen: 500 */
- var txt = [
- 'An error has occurred. Wait a few minutes and then try to submit the application again.',
- 'If you continue to have issues please contact support.'
- ],
- msg = gettext(txt.join(' '));
+ saveError: function(error) {
+ /* jslint maxlen: 500 */
+ var txt = [
+ 'An error has occurred. Wait a few minutes and then try to submit the application again.',
+ 'If you continue to have issues please contact support.'
+ ],
+ msg = gettext(txt.join(' '));
- if (error.status === 0) {
- msg = gettext('An error has occurred. Check your Internet connection and try again.');
- }
+ if (error.status === 0) {
+ msg = gettext('An error has occurred. Check your Internet connection and try again.');
+ }
- this.errors = ['' + msg + ''];
- this.setErrors();
- this.element.hide( this.$resetSuccess );
- this.toggleDisableButton(false);
- },
+ this.errors = ['' + msg + ''];
+ this.setErrors();
+ this.element.hide(this.$resetSuccess);
+ this.toggleDisableButton(false);
+ },
- setExtraData: function(data) {
- return _.extend(data, this.user_details);
- },
+ setExtraData: function(data) {
+ return _.extend(data, this.user_details);
+ },
- validateCountry: function() {
- var $submissionContainer = $('.submission-error'),
- $errorMessageContainer = $submissionContainer.find('.message-copy'),
- $countryLabel = $('#user-country-title'),
- txt = [
- 'Please go to your {link_start}profile page{link_end} ',
- 'and provide your country of residence.'
- ],
- msg = window.interpolate_text(
+ validateCountry: function() {
+ var $submissionContainer = $('.submission-error'),
+ $errorMessageContainer = $submissionContainer.find('.message-copy'),
+ $countryLabel = $('#user-country-title'),
+ txt = [
+ 'Please go to your {link_start}profile page{link_end} ',
+ 'and provide your country of residence.'
+ ],
+ msg = window.interpolate_text(
// Translators: link_start and link_end denote the html to link back to the profile page.
gettext(txt.join('')),
- {
- link_start: '',
- link_end: ''
- }
+ {
+ link_start: '',
+ link_end: ''
+ }
);
- if( !this.model.get('country') ){
- $countryLabel.addClass('error');
- $errorMessageContainer.append("" + msg + "");
- this.toggleDisableButton(true);
- $submissionContainer.removeClass('hidden');
- }
- },
+ if (!this.model.get('country')) {
+ $countryLabel.addClass('error');
+ $errorMessageContainer.append('' + msg + '');
+ this.toggleDisableButton(true);
+ $submissionContainer.removeClass('hidden');
+ }
+ },
- addDefaultOption: function(array, index) {
- if ( array[index].options.length > 1 ) {
- array[index].options.unshift({
- name: '- ' + gettext('Choose one') + ' -',
- value: '',
- default: true
- });
- }
- }
- });
- }
+ addDefaultOption: function(array, index) {
+ if (array[index].options.length > 1) {
+ array[index].options.unshift({
+ name: '- ' + gettext('Choose one') + ' -',
+ value: '',
+ default: true
+ });
+ }
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/footer-edx.js b/lms/static/js/footer-edx.js
index 0b388d1aa6..8a14301369 100644
--- a/lms/static/js/footer-edx.js
+++ b/lms/static/js/footer-edx.js
@@ -9,35 +9,35 @@ var edx = edx || {};
analytics: {
init: function() {
- _fn.$el = _fn.$el || $( _fn.el );
+ _fn.$el = _fn.$el || $(_fn.el);
/**
* Only continue if the expected element
* to add footer to is in the DOM
*/
- if ( _fn.$el.length ) {
+ if (_fn.$el.length) {
_fn.analytics.eventListener();
}
},
eventListener: function() {
- if ( window.analytics ) {
- _fn.$el.on( 'click', 'a', _fn.analytics.track );
+ if (window.analytics) {
+ _fn.$el.on('click', 'a', _fn.analytics.track);
}
},
- track: function( event ) {
- var $link = $( event.currentTarget );
+ track: function(event) {
+ var $link = $(event.currentTarget);
// Only tracking external links
- if ( $link.hasClass('external') ) {
- window.analytics.track( 'edx.bi.footer.link', {
+ if ($link.hasClass('external')) {
+ window.analytics.track('edx.bi.footer.link', {
category: 'outbound_link',
label: $link.attr('href')
});
}
}
- },
+ }
};
return {
diff --git a/lms/static/js/form.ext.js b/lms/static/js/form.ext.js
index c64872a1e9..f3848cb424 100644
--- a/lms/static/js/form.ext.js
+++ b/lms/static/js/form.ext.js
@@ -1,44 +1,43 @@
(function($, undefined) {
- var form_ext;
- $.form_ext = form_ext = {
- ajax: function(options) {
- return $.ajax(options);
- },
- handleRemote: function(element) {
- var method = element.attr('method');
- var url = element.attr('action');
- var data = element.serializeArray();
- var options = {
- type: method || 'GET',
- data: data,
- dataType: 'text json',
- success: function(data, status, xhr) {
- element.trigger("ajax:success", [data, status, xhr]);
+ var form_ext;
+ $.form_ext = form_ext = {
+ ajax: function(options) {
+ return $.ajax(options);
},
- complete: function(xhr, status) {
- element.trigger("ajax:complete", [xhr, status]);
+ handleRemote: function(element) {
+ var method = element.attr('method');
+ var url = element.attr('action');
+ var data = element.serializeArray();
+ var options = {
+ type: method || 'GET',
+ data: data,
+ dataType: 'text json',
+ success: function(data, status, xhr) {
+ element.trigger('ajax:success', [data, status, xhr]);
+ },
+ complete: function(xhr, status) {
+ element.trigger('ajax:complete', [xhr, status]);
+ },
+ error: function(xhr, status, error) {
+ element.trigger('ajax:error', [xhr, status, error]);
+ }
+ };
+ if (url) { options.url = url; }
+ return form_ext.ajax(options);
},
- error: function(xhr, status, error) {
- element.trigger("ajax:error", [xhr, status, error]);
+ CSRFProtection: function(xhr) {
+ var token = $.cookie('csrftoken');
+ if (token) xhr.setRequestHeader('X-CSRFToken', token);
}
- }
- if(url) { options.url = url; }
- return form_ext.ajax(options)
- },
- CSRFProtection: function(xhr) {
- var token = $.cookie('csrftoken');
- if (token) xhr.setRequestHeader('X-CSRFToken', token);
- }
- }
- $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { form_ext.CSRFProtection(xhr); }});
- $(document).delegate('form', 'submit', function(e) {
- var form = $(this),
- remote = form.data("remote") !== undefined;
+ };
+ $.ajaxPrefilter(function(options, originalOptions, xhr) { if (!options.crossDomain) { form_ext.CSRFProtection(xhr); } });
+ $(document).delegate('form', 'submit', function(e) {
+ var form = $(this),
+ remote = form.data('remote') !== undefined;
- if(remote) {
- form_ext.handleRemote(form);
- return false;
- }
-
- });
+ if (remote) {
+ form_ext.handleRemote(form);
+ return false;
+ }
+ });
})(jQuery);
diff --git a/lms/static/js/groups/collections/cohort.js b/lms/static/js/groups/collections/cohort.js
index 2f74cb69f7..611725a2dd 100644
--- a/lms/static/js/groups/collections/cohort.js
+++ b/lms/static/js/groups/collections/cohort.js
@@ -1,10 +1,9 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone', 'js/groups/models/cohort'], function(Backbone, CohortModel) {
-
var CohortCollection = Backbone.Collection.extend({
- model : CohortModel,
- comparator: "name",
+ model: CohortModel,
+ comparator: 'name',
parse: function(response) {
return response.cohorts;
diff --git a/lms/static/js/groups/models/cohort.js b/lms/static/js/groups/models/cohort.js
index 7b0ded9e10..acdd8ea4b0 100644
--- a/lms/static/js/groups/models/cohort.js
+++ b/lms/static/js/groups/models/cohort.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
-
var CohortModel = Backbone.Model.extend({
idAttribute: 'id',
defaults: {
diff --git a/lms/static/js/groups/models/cohort_discussions.js b/lms/static/js/groups/models/cohort_discussions.js
index b44d8513a7..8a309cb96b 100644
--- a/lms/static/js/groups/models/cohort_discussions.js
+++ b/lms/static/js/groups/models/cohort_discussions.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
var DiscussionTopicsSettingsModel = Backbone.Model.extend({
diff --git a/lms/static/js/groups/models/content_group.js b/lms/static/js/groups/models/content_group.js
index 313647ffd8..879320c835 100644
--- a/lms/static/js/groups/models/content_group.js
+++ b/lms/static/js/groups/models/content_group.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
var ContentGroupModel = Backbone.Model.extend({
diff --git a/lms/static/js/groups/models/course_cohort_settings.js b/lms/static/js/groups/models/course_cohort_settings.js
index 77dc6662cf..11a88dedf0 100644
--- a/lms/static/js/groups/models/course_cohort_settings.js
+++ b/lms/static/js/groups/models/course_cohort_settings.js
@@ -1,13 +1,12 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
-
var CourseCohortSettingsModel = Backbone.Model.extend({
idAttribute: 'id',
defaults: {
is_cohorted: false,
cohorted_inline_discussions: [],
- cohorted_course_wide_discussions:[],
+ cohorted_course_wide_discussions: [],
always_cohort_inline_discussions: true
}
});
diff --git a/lms/static/js/groups/models/verified_track_settings.js b/lms/static/js/groups/models/verified_track_settings.js
index 2fad6a499c..68a584bd6a 100644
--- a/lms/static/js/groups/models/verified_track_settings.js
+++ b/lms/static/js/groups/models/verified_track_settings.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
var VerifiedTrackSettingsModel = Backbone.Model.extend({
diff --git a/lms/static/js/groups/views/cohort_discussions.js b/lms/static/js/groups/views/cohort_discussions.js
index d0e8fed597..8b13aa5056 100644
--- a/lms/static/js/groups/views/cohort_discussions.js
+++ b/lms/static/js/groups/views/cohort_discussions.js
@@ -1,8 +1,7 @@
-;(function (define) {
+(function(define) {
'use strict';
- define(['jquery', 'underscore', 'backbone', 'gettext', 'js/models/notification', 'js/views/notification'],
- function ($, _, Backbone) {
-
+ define(['jquery', 'underscore', 'backbone', 'gettext', 'js/models/notification', 'js/views/notification'],
+ function($, _, Backbone) {
var CohortDiscussionConfigurationView = Backbone.View.extend({
/**
@@ -20,11 +19,11 @@
* @returns {Array} - Cohorted discussions.
*/
getCohortedDiscussions: function(selector) {
- var self=this,
+ var self = this,
cohortedDiscussions = [];
- _.each(self.$(selector), function (topic) {
- cohortedDiscussions.push($(topic).data('id'))
+ _.each(self.$(selector), function(topic) {
+ cohortedDiscussions.push($(topic).data('id'));
});
return cohortedDiscussions;
},
@@ -35,22 +34,22 @@
* @param {object} $element - Messages would be shown before this element.
* @param {object} fieldData - Data to update on the server.
*/
- saveForm: function ($element, fieldData) {
+ saveForm: function($element, fieldData) {
var self = this,
cohortSettingsModel = this.cohortSettings,
saveOperation = $.Deferred(),
showErrorMessage;
- showErrorMessage = function (message, $element) {
+ showErrorMessage = function(message, $element) {
self.showMessage(message, $element, 'error');
};
this.removeNotification();
cohortSettingsModel.save(
fieldData, {patch: true, wait: true}
- ).done(function () {
+ ).done(function() {
saveOperation.resolve();
- }).fail(function (result) {
+ }).fail(function(result) {
var errorMessage = null;
try {
var jsonResponse = JSON.parse(result.responseText);
@@ -73,7 +72,7 @@
* @param {object} $element - Message would be shown before this element.
* @param {string} type - Type of message to show e.g. confirmation or error.
*/
- showMessage: function (message, $element, type) {
+ showMessage: function(message, $element, type) {
var model = new NotificationModel({type: type || 'confirmation', title: message});
this.removeNotification();
this.notification = new NotificationView({
@@ -86,7 +85,7 @@
/**
*Removes the notification messages.
*/
- removeNotification: function () {
+ removeNotification: function() {
if (this.notification) {
this.notification.remove();
}
diff --git a/lms/static/js/groups/views/cohort_discussions_course_wide.js b/lms/static/js/groups/views/cohort_discussions_course_wide.js
index 0873be734b..3a4b400ebc 100644
--- a/lms/static/js/groups/views/cohort_discussions_course_wide.js
+++ b/lms/static/js/groups/views/cohort_discussions_course_wide.js
@@ -1,20 +1,20 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone', 'gettext', 'js/groups/views/cohort_discussions',
'edx-ui-toolkit/js/utils/html-utils'],
- function ($, _, Backbone, gettext, CohortDiscussionConfigurationView, HtmlUtils) {
+ function($, _, Backbone, gettext, CohortDiscussionConfigurationView, HtmlUtils) {
var CourseWideDiscussionsView = CohortDiscussionConfigurationView.extend({
events: {
'change .check-discussion-subcategory-course-wide': 'discussionCategoryStateChanged',
'click .cohort-course-wide-discussions-form .action-save': 'saveCourseWideDiscussionsForm'
},
- initialize: function (options) {
+ initialize: function(options) {
this.template = HtmlUtils.template($('#cohort-discussions-course-wide-tpl').text());
this.cohortSettings = options.cohortSettings;
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$('.cohort-course-wide-discussions-nav'), this.template({
courseWideTopicsHtml: this.getCourseWideDiscussionsHtml(
this.model.get('course_wide_discussions')
@@ -28,12 +28,12 @@
* @param {object} courseWideDiscussions - course-wide discussions object from server.
* @returns {HtmlSnippet} - HTML list for course-wide discussion topics.
*/
- getCourseWideDiscussionsHtml: function (courseWideDiscussions) {
+ getCourseWideDiscussionsHtml: function(courseWideDiscussions) {
var subCategoryTemplate = HtmlUtils.template($('#cohort-discussions-subcategory-tpl').html()),
entries = courseWideDiscussions.entries,
children = courseWideDiscussions.children;
- return HtmlUtils.joinHtml.apply(this, _.map(children, function (name) {
+ return HtmlUtils.joinHtml.apply(this, _.map(children, function(name) {
var entry = entries[name];
return subCategoryTemplate({
name: name,
@@ -55,29 +55,29 @@
/**
* Sends the cohorted_course_wide_discussions to the server and renders the view.
*/
- saveCourseWideDiscussionsForm: function (event) {
+ saveCourseWideDiscussionsForm: function(event) {
event.preventDefault();
var self = this,
courseWideCohortedDiscussions = self.getCohortedDiscussions(
'.check-discussion-subcategory-course-wide:checked'
),
- fieldData = { cohorted_course_wide_discussions: courseWideCohortedDiscussions };
+ fieldData = {cohorted_course_wide_discussions: courseWideCohortedDiscussions};
- self.saveForm(self.$('.course-wide-discussion-topics'),fieldData)
- .done(function () {
+ self.saveForm(self.$('.course-wide-discussion-topics'), fieldData)
+ .done(function() {
self.model.fetch()
- .done(function () {
+ .done(function() {
self.render();
self.showMessage(gettext('Your changes have been saved.'), self.$('.course-wide-discussion-topics'));
}).fail(function() {
var errorMessage = gettext("We've encountered an error. Refresh your browser and then try again.");
- self.showMessage(errorMessage, self.$('.course-wide-discussion-topics'), 'error')
+ self.showMessage(errorMessage, self.$('.course-wide-discussion-topics'), 'error');
});
});
}
});
return CourseWideDiscussionsView;
- });
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/groups/views/cohort_discussions_inline.js b/lms/static/js/groups/views/cohort_discussions_inline.js
index ea55c733d5..9b0f5acb98 100644
--- a/lms/static/js/groups/views/cohort_discussions_inline.js
+++ b/lms/static/js/groups/views/cohort_discussions_inline.js
@@ -1,8 +1,8 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone', 'gettext', 'js/groups/views/cohort_discussions',
'edx-ui-toolkit/js/utils/html-utils', 'js/vendor/jquery.qubit'],
- function ($, _, Backbone, gettext, CohortDiscussionConfigurationView, HtmlUtils) {
+ function($, _, Backbone, gettext, CohortDiscussionConfigurationView, HtmlUtils) {
var InlineDiscussionsView = CohortDiscussionConfigurationView.extend({
events: {
'change .check-discussion-category': 'setSaveButton',
@@ -12,18 +12,18 @@
'change .check-cohort-inline-discussions': 'setSomeInlineDiscussions'
},
- initialize: function (options) {
+ initialize: function(options) {
this.template = HtmlUtils.template($('#cohort-discussions-inline-tpl').text());
this.cohortSettings = options.cohortSettings;
},
- render: function () {
+ render: function() {
var alwaysCohortInlineDiscussions = this.cohortSettings.get('always_cohort_inline_discussions'),
inline_discussions = this.model.get('inline_discussions');
HtmlUtils.setHtml(this.$('.cohort-inline-discussions-nav'), this.template({
inlineDiscussionTopicsHtml: this.getInlineDiscussionsHtml(inline_discussions),
- alwaysCohortInlineDiscussions:alwaysCohortInlineDiscussions
+ alwaysCohortInlineDiscussions: alwaysCohortInlineDiscussions
}));
// Provides the semantics for a nested list of tri-state checkboxes.
@@ -40,7 +40,7 @@
* @params {object} inlineDiscussions - inline discussions object from server.
* @returns {HtmlSnippet} - HTML for inline discussion topics.
*/
- getInlineDiscussionsHtml: function (inlineDiscussions) {
+ getInlineDiscussionsHtml: function(inlineDiscussions) {
var categoryTemplate = HtmlUtils.template($('#cohort-discussions-category-tpl').html()),
entryTemplate = HtmlUtils.template($('#cohort-discussions-subcategory-tpl').html()),
isCategoryCohorted = false,
@@ -48,7 +48,7 @@
entries = inlineDiscussions.entries,
subcategories = inlineDiscussions.subcategories;
- return HtmlUtils.joinHtml.apply(this, _.map(children, function (name) {
+ return HtmlUtils.joinHtml.apply(this, _.map(children, function(name) {
var htmlSnippet = '', entry;
if (entries && _.has(entries, name)) {
entry = entries[name];
@@ -115,32 +115,32 @@
/**
* Sends the cohorted_inline_discussions to the server and renders the view.
*/
- saveInlineDiscussionsForm: function (event) {
+ saveInlineDiscussionsForm: function(event) {
event.preventDefault();
var self = this,
cohortedInlineDiscussions = self.getCohortedDiscussions(
'.check-discussion-subcategory-inline:checked'
),
- fieldData= {
+ fieldData = {
cohorted_inline_discussions: cohortedInlineDiscussions,
always_cohort_inline_discussions: self.$('.check-all-inline-discussions').prop('checked')
};
self.saveForm(self.$('.inline-discussion-topics'), fieldData)
- .done(function () {
+ .done(function() {
self.model.fetch()
- .done(function () {
+ .done(function() {
self.render();
self.showMessage(gettext('Your changes have been saved.'), self.$('.inline-discussion-topics'));
}).fail(function() {
var errorMessage = gettext("We've encountered an error. Refresh your browser and then try again.");
- self.showMessage(errorMessage, self.$('.inline-discussion-topics'), 'error')
+ self.showMessage(errorMessage, self.$('.inline-discussion-topics'), 'error');
});
});
}
+ });
+ return InlineDiscussionsView;
});
- return InlineDiscussionsView;
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/groups/views/cohort_editor.js b/lms/static/js/groups/views/cohort_editor.js
index 78763424f3..2c65cd0ff6 100644
--- a/lms/static/js/groups/views/cohort_editor.js
+++ b/lms/static/js/groups/views/cohort_editor.js
@@ -1,11 +1,11 @@
-;(function (define) {
+(function(define) {
'use strict';
- define(['backbone', 'underscore', 'jquery', 'gettext', 'js/groups/views/cohort_form', 'string_utils',
+ define(['backbone', 'underscore', 'jquery', 'gettext', 'js/groups/views/cohort_form', 'string_utils',
'js/models/notification', 'js/views/notification'],
function(Backbone, _, $, gettext, CohortFormView) {
var CohortEditorView = Backbone.View.extend({
- events : {
+ events: {
'click .wrapper-tabs .tab': 'selectTab',
'click .tab-content-settings .action-save': 'saveSettings',
'click .tab-content-settings .action-cancel': 'cancelSettings',
@@ -123,7 +123,7 @@
return this.cohorts.fetch();
},
- undelegateViewEvents: function (view) {
+ undelegateViewEvents: function(view) {
if (view) {
view.undelegateEvents();
}
@@ -161,13 +161,13 @@
numPresent = modifiedUsers.present.length;
if (numUsersAdded > 0 || numPresent > 0) {
title = interpolate_text(
- ngettext("{numUsersAdded} student has been added to this cohort",
- "{numUsersAdded} students have been added to this cohort", numUsersAdded),
+ ngettext('{numUsersAdded} student has been added to this cohort',
+ '{numUsersAdded} students have been added to this cohort', numUsersAdded),
{numUsersAdded: numUsersAdded}
);
var movedByCohort = {};
- _.each(modifiedUsers.changed, function (changedInfo) {
+ _.each(modifiedUsers.changed, function(changedInfo) {
oldCohort = changedInfo.previous_cohort;
if (oldCohort in movedByCohort) {
movedByCohort[oldCohort] = movedByCohort[oldCohort] + 1;
@@ -181,8 +181,8 @@
for (oldCohort in movedByCohort) {
details.push(
interpolate_text(
- ngettext("{numMoved} student was removed from {oldCohort}",
- "{numMoved} students were removed from {oldCohort}", movedByCohort[oldCohort]),
+ ngettext('{numMoved} student was removed from {oldCohort}',
+ '{numMoved} students were removed from {oldCohort}', movedByCohort[oldCohort]),
{numMoved: movedByCohort[oldCohort], oldCohort: oldCohort}
)
);
@@ -190,8 +190,8 @@
if (numPresent > 0) {
details.push(
interpolate_text(
- ngettext("{numPresent} student was already in the cohort",
- "{numPresent} students were already in the cohort", numPresent),
+ ngettext('{numPresent} student was already in the cohort',
+ '{numPresent} students were already in the cohort', numPresent),
{numPresent: numPresent}
)
);
@@ -200,7 +200,7 @@
this.confirmationNotifications = new NotificationView({
el: this.$('.cohort-confirmations'),
model: new NotificationModel({
- type: "confirmation",
+ type: 'confirmation',
title: title,
details: details
})
@@ -216,31 +216,31 @@
this.undelegateViewEvents(this.errorNotifications);
numErrors = modifiedUsers.unknown.length;
if (numErrors > 0) {
- createErrorDetails = function (unknownUsers, showAllErrors) {
+ createErrorDetails = function(unknownUsers, showAllErrors) {
var numErrors = unknownUsers.length, details = [];
for (var i = 0; i < (showAllErrors ? numErrors : Math.min(errorLimit, numErrors)); i++) {
- details.push(interpolate_text(gettext("Unknown user: {user}"), {user: unknownUsers[i]}));
+ details.push(interpolate_text(gettext('Unknown user: {user}'), {user: unknownUsers[i]}));
}
return details;
};
title = interpolate_text(
- ngettext("There was an error when trying to add students:",
- "There were {numErrors} errors when trying to add students:", numErrors),
+ ngettext('There was an error when trying to add students:',
+ 'There were {numErrors} errors when trying to add students:', numErrors),
{numErrors: numErrors}
);
details = createErrorDetails(modifiedUsers.unknown, false);
- errorActionCallback = function (view) {
- view.model.set("actionText", null);
- view.model.set("details", createErrorDetails(modifiedUsers.unknown, true));
+ errorActionCallback = function(view) {
+ view.model.set('actionText', null);
+ view.model.set('details', createErrorDetails(modifiedUsers.unknown, true));
view.render();
};
errorModel = new NotificationModel({
details: details,
- actionText: numErrors > errorLimit ? gettext("View all errors") : null,
+ actionText: numErrors > errorLimit ? gettext('View all errors') : null,
actionCallback: errorActionCallback,
actionClass: 'action-expand'
});
@@ -254,5 +254,5 @@
}
});
return CohortEditorView;
- });
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/groups/views/cohort_form.js b/lms/static/js/groups/views/cohort_form.js
index f313e5ff85..1d7c987232 100644
--- a/lms/static/js/groups/views/cohort_form.js
+++ b/lms/static/js/groups/views/cohort_form.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone', 'gettext', 'edx-ui-toolkit/js/utils/html-utils',
'js/models/notification', 'js/views/notification'],
function($, _, Backbone, gettext, HtmlUtils) {
-
var CohortFormView = Backbone.View.extend({
- events : {
+ events: {
'change .cohort-management-details-association-course input': 'onRadioButtonChange'
},
@@ -46,7 +45,7 @@
if (_.isUndefined(cohorts)) {
return false;
}
- var randomModels = cohorts.where({assignment_type:'random'});
+ var randomModels = cohorts.where({assignment_type: 'random'});
return (randomModels.length === 1) && (randomModels[0].get('name') === name);
},
@@ -75,7 +74,7 @@
ids = selectValue.split(':');
groupId = parseInt(ids[0]);
userPartitionId = parseInt(ids[1]);
- for (i=0; i < this.contentGroups.length; i++) {
+ for (i = 0; i < this.contentGroups.length; i++) {
contentGroup = this.contentGroups[i];
if (contentGroup.get('id') === groupId && contentGroup.get('user_partition_id') === userPartitionId) {
return contentGroup;
@@ -139,7 +138,7 @@
if (errorMessages.length > 0) {
showErrorMessage(
- isUpdate ? gettext("The cohort cannot be saved") : gettext("The cohort cannot be added"),
+ isUpdate ? gettext('The cohort cannot be saved') : gettext('The cohort cannot be added'),
errorMessages
);
saveOperation.reject();
@@ -155,7 +154,7 @@
try {
var jsonResponse = JSON.parse(result.responseText);
errorMessage = jsonResponse.error;
- } catch(e) {
+ } catch (e) {
// Ignore the exception and show the default error message instead.
}
if (!errorMessage) {
diff --git a/lms/static/js/groups/views/cohorts.js b/lms/static/js/groups/views/cohorts.js
index 2b680aea45..63b60e0c30 100644
--- a/lms/static/js/groups/views/cohorts.js
+++ b/lms/static/js/groups/views/cohorts.js
@@ -1,8 +1,8 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone', 'gettext', 'js/groups/models/cohort',
'js/groups/models/verified_track_settings',
- 'js/groups/views/cohort_editor', 'js/groups/views/cohort_form',
+ 'js/groups/views/cohort_editor', 'js/groups/views/cohort_form',
'js/groups/views/course_cohort_settings_notification',
'js/groups/views/cohort_discussions_inline', 'js/groups/views/cohort_discussions_course_wide',
'js/groups/views/verified_track_settings_notification',
@@ -11,14 +11,13 @@
function($, _, Backbone, gettext, CohortModel, VerifiedTrackSettingsModel, CohortEditorView, CohortFormView,
CourseCohortSettingsNotificationView, InlineDiscussionsView, CourseWideDiscussionsView,
VerifiedTrackSettingsNotificationView, HtmlUtils) {
-
var hiddenClass = 'is-hidden',
disabledClass = 'is-disabled',
enableCohortsSelector = '.cohorts-state';
var CohortsView = Backbone.View.extend({
- events : {
+ events: {
'change .cohort-select': 'onCohortSelected',
'change .cohorts-state': 'onCohortsEnabledChanged',
'click .action-create': 'showAddCohortForm',
@@ -42,7 +41,7 @@
// Update cohort counts when the user clicks back on the cohort management tab
// (for example, after uploading a csv file of cohort assignments and then
// checking results on data download tab).
- $(this.getSectionCss('cohort_management')).click(function () {
+ $(this.getSectionCss('cohort_management')).click(function() {
model.fetch();
});
},
@@ -275,7 +274,7 @@
showSection: function(event) {
event.preventDefault();
- var section = $(event.currentTarget).data("section");
+ var section = $(event.currentTarget).data('section');
$(this.getSectionCss(section)).click();
$(window).scrollTop(0);
},
@@ -289,18 +288,18 @@
if (!this.fileUploaderView) {
this.fileUploaderView = new FileUploaderView({
el: uploadElement,
- title: gettext("Assign students to cohorts by uploading a CSV file."),
- inputLabel: gettext("Choose a .csv file"),
- inputTip: gettext("Only properly formatted .csv files will be accepted."),
- submitButtonText: gettext("Upload File and Assign Students"),
- extensions: ".csv",
+ title: gettext('Assign students to cohorts by uploading a CSV file.'),
+ inputLabel: gettext('Choose a .csv file'),
+ inputTip: gettext('Only properly formatted .csv files will be accepted.'),
+ submitButtonText: gettext('Upload File and Assign Students'),
+ extensions: '.csv',
url: this.context.uploadCohortsCsvUrl,
- successNotification: function (file, event, data) {
+ successNotification: function(file, event, data) {
var message = interpolate_text(gettext(
"Your file '{file}' has been uploaded. Allow a few minutes for processing."
), {file: file});
return new NotificationModel({
- type: "confirmation",
+ type: 'confirmation',
title: message
});
}
@@ -321,7 +320,7 @@
cohortSettings: this.cohortSettings
}).render();
}
- if(!this.InlineDiscussionsView) {
+ if (!this.InlineDiscussionsView) {
this.InlineDiscussionsView = new InlineDiscussionsView({
el: cohortDiscussionsElement,
model: this.context.discussionTopicsSettingsModel,
@@ -330,10 +329,10 @@
}
},
- getSectionCss: function (section) {
+ getSectionCss: function(section) {
return ".instructor-nav .nav-item a[data-section='" + section + "']";
}
});
return CohortsView;
- });
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/groups/views/cohorts_dashboard_factory.js b/lms/static/js/groups/views/cohorts_dashboard_factory.js
index c3d36dae82..af63d0c676 100644
--- a/lms/static/js/groups/views/cohorts_dashboard_factory.js
+++ b/lms/static/js/groups/views/cohorts_dashboard_factory.js
@@ -1,9 +1,8 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['jquery', 'js/groups/views/cohorts', 'js/groups/collections/cohort', 'js/groups/models/course_cohort_settings',
'js/groups/models/cohort_discussions', 'js/groups/models/content_group'],
function($, CohortsView, CohortCollection, CourseCohortSettingsModel, DiscussionTopicsSettingsModel, ContentGroupModel) {
-
return function(contentGroups, studioGroupConfigurationsUrl) {
var contentGroupModels = $.map(contentGroups, function(group) {
return new ContentGroupModel({
@@ -22,7 +21,7 @@
cohorts.url = cohortManagementElement.data('cohorts_url');
courseCohortSettings.url = cohortManagementElement.data('course_cohort_settings_url');
discussionTopicsSettings.url = cohortManagementElement.data('discussion-topics-url');
-
+
var cohortsView = new CohortsView({
el: cohortManagementElement,
model: cohorts,
@@ -44,6 +43,6 @@
});
});
};
- });
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/groups/views/course_cohort_settings_notification.js b/lms/static/js/groups/views/course_cohort_settings_notification.js
index 78ba1e30e7..5d5aaa1f8d 100644
--- a/lms/static/js/groups/views/course_cohort_settings_notification.js
+++ b/lms/static/js/groups/views/course_cohort_settings_notification.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone', 'gettext'], function($, _, Backbone, gettext) {
-
var CourseCohortSettingsNotificationView = Backbone.View.extend({
initialize: function(options) {
this.template = _.template($('#cohort-state-tpl').text());
@@ -14,7 +13,7 @@
return this;
},
- showCohortStateMessage: function () {
+ showCohortStateMessage: function() {
var actionToggleMessage = this.$('.action-toggle-message');
AnimationUtil.triggerAnimation(actionToggleMessage);
diff --git a/lms/static/js/groups/views/verified_track_settings_notification.js b/lms/static/js/groups/views/verified_track_settings_notification.js
index 54d0ff4c82..b8aa9f5bff 100644
--- a/lms/static/js/groups/views/verified_track_settings_notification.js
+++ b/lms/static/js/groups/views/verified_track_settings_notification.js
@@ -1,32 +1,32 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone', 'gettext', 'edx-ui-toolkit/js/utils/string-utils',
'js/models/notification', 'js/views/notification'],
- function ($, _, Backbone, gettext, StringUtils) {
- /*global NotificationModel, NotificationView */
+ function($, _, Backbone, gettext, StringUtils) {
+ /* global NotificationModel, NotificationView */
var VerifiedTrackSettingsNotificationView = Backbone.View.extend({
- render: function () {
+ render: function() {
// All rendering is done in validateSettings, which must be called with some additional information.
return this;
},
- validateSettings: function (isCohorted, cohortCollection, enableCohortsCheckbox) {
+ validateSettings: function(isCohorted, cohortCollection, enableCohortsCheckbox) {
if (this.model.get('enabled')) {
var verifiedCohortName = this.model.get('verified_cohort_name');
if (isCohorted) {
var verifiedCohortExists = false;
- $.each(cohortCollection, function (_, cohort) {
- if (cohort.get('assignment_type') === 'manual' &&
+ $.each(cohortCollection, function(_, cohort) {
+ if (cohort.get('assignment_type') === 'manual' &&
cohort.get('name') === verifiedCohortName) {
- verifiedCohortExists = true;
- cohort.disableEditingName = true;
- }
- else {
- cohort.disableEditingName = false;
- }
+ verifiedCohortExists = true;
+ cohort.disableEditingName = true;
}
+ else {
+ cohort.disableEditingName = false;
+ }
+ }
);
if (verifiedCohortExists) {
this.showNotification({
@@ -36,7 +36,6 @@
{verifiedCohortName: verifiedCohortName}
)
});
-
}
else {
this.showNotification({
@@ -59,7 +58,7 @@
}
},
- showNotification: function (options) {
+ showNotification: function(options) {
if (this.notification) {
this.notification.remove();
}
diff --git a/lms/static/js/header_factory.js b/lms/static/js/header_factory.js
index 507daaf634..c4a25284e3 100644
--- a/lms/static/js/header_factory.js
+++ b/lms/static/js/header_factory.js
@@ -1,10 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'edx-ui-toolkit/js/dropdown-menu/dropdown-menu-view'
],
- function (DropdownMenuView) {
+ function(DropdownMenuView) {
return function() {
var dropdownMenuView = new DropdownMenuView({
el: '.js-header-user-menu'
diff --git a/lms/static/js/instructor_dashboard/certificates.js b/lms/static/js/instructor_dashboard/certificates.js
index b25e50c0ba..de48111db9 100644
--- a/lms/static/js/instructor_dashboard/certificates.js
+++ b/lms/static/js/instructor_dashboard/certificates.js
@@ -12,17 +12,17 @@ var onCertificatesReady = null;
* Show a confirmation message before letting staff members
* enable/disable self-generated certificates for a course.
*/
- $('#enable-certificates-form').on('submit', function( event ) {
+ $('#enable-certificates-form').on('submit', function(event) {
var isEnabled = $('#certificates-enabled').val() === 'true',
confirmMessage = '';
- if ( isEnabled ) {
+ if (isEnabled) {
confirmMessage = gettext('Allow students to generate certificates for this course?');
} else {
confirmMessage = gettext('Prevent students from generating certificates in this course?');
}
- if ( !confirm( confirmMessage ) ) {
+ if (!confirm(confirmMessage)) {
event.preventDefault();
}
});
@@ -39,20 +39,20 @@ var onCertificatesReady = null;
/**
* Start generating certificates for all students.
*/
- var $section = $("section#certificates");
+ var $section = $('section#certificates');
$section.on('click', '#btn-start-generating-certificates', function(event) {
- if ( !confirm( gettext('Start generating certificates for all students in this course?') ) ) {
+ if (!confirm(gettext('Start generating certificates for all students in this course?'))) {
event.preventDefault();
return;
}
- var $btn_generating_certs = $(this),$certificate_generation_status = $('.certificate-generation-status');
+ var $btn_generating_certs = $(this), $certificate_generation_status = $('.certificate-generation-status');
var url = $btn_generating_certs.data('endpoint');
$.ajax({
- type: "POST",
+ type: 'POST',
url: url,
- success: function (data) {
- $btn_generating_certs.attr('disabled','disabled');
+ success: function(data) {
+ $btn_generating_certs.attr('disabled', 'disabled');
$certificate_generation_status.text(data.message);
},
error: function(jqXHR, textStatus, errorThrown) {
@@ -65,7 +65,7 @@ var onCertificatesReady = null;
* Start regenerating certificates for students.
*/
$section.on('click', '#btn-start-regenerating-certificates', function(event) {
- if ( !confirm( gettext('Start regenerating certificates for students in this course?') ) ) {
+ if (!confirm(gettext('Start regenerating certificates for students in this course?'))) {
event.preventDefault();
return;
}
@@ -75,26 +75,26 @@ var onCertificatesReady = null;
url = $btn_regenerating_certs.data('endpoint');
$.ajax({
- type: "POST",
- data: $("#certificate-regenerating-form").serializeArray(),
+ type: 'POST',
+ data: $('#certificate-regenerating-form').serializeArray(),
url: url,
- success: function (data) {
- $btn_regenerating_certs.attr('disabled','disabled');
- if(data.success){
- $certificate_regeneration_status.text(data.message).addClass("message");
+ success: function(data) {
+ $btn_regenerating_certs.attr('disabled', 'disabled');
+ if (data.success) {
+ $certificate_regeneration_status.text(data.message).addClass('message');
}
- else{
- $certificate_regeneration_status.text(data.message).addClass("message");
+ else {
+ $certificate_regeneration_status.text(data.message).addClass('message');
}
},
error: function(jqXHR) {
- try{
+ try {
var response = JSON.parse(jqXHR.responseText);
- $certificate_regeneration_status.text(gettext(response.message)).addClass("message");
- }catch(error){
+ $certificate_regeneration_status.text(gettext(response.message)).addClass('message');
+ } catch (error) {
$certificate_regeneration_status.
text(gettext('Error while regenerating certificates. Please try again.')).
- addClass("message");
+ addClass('message');
}
}
});
@@ -131,5 +131,4 @@ var onCertificatesReady = null;
_.defaults(window.InstructorDashboard.sections, {
Certificates: Certificates
});
-
})($, gettext, _);
diff --git a/lms/static/js/instructor_dashboard/cohort_management.js b/lms/static/js/instructor_dashboard/cohort_management.js
index abe725f21a..e43c3717bb 100644
--- a/lms/static/js/instructor_dashboard/cohort_management.js
+++ b/lms/static/js/instructor_dashboard/cohort_management.js
@@ -2,18 +2,15 @@
var CohortManagement;
CohortManagement = (function() {
+ function CohortManagement($section) {
+ this.$section = $section;
+ this.$section.data('wrapper', this);
+ }
- function CohortManagement($section) {
- this.$section = $section;
- this.$section.data('wrapper', this);
- }
-
- CohortManagement.prototype.onClickTitle = function() {};
-
- return CohortManagement;
+ CohortManagement.prototype.onClickTitle = function() {};
+ return CohortManagement;
})();
window.InstructorDashboard.sections.CohortManagement = CohortManagement;
-
}).call(this);
diff --git a/lms/static/js/instructor_dashboard/ecommerce.js b/lms/static/js/instructor_dashboard/ecommerce.js
index 7f2f67d06c..167448809b 100644
--- a/lms/static/js/instructor_dashboard/ecommerce.js
+++ b/lms/static/js/instructor_dashboard/ecommerce.js
@@ -15,7 +15,7 @@ var edx = edx || {};
$('li#add-coupon-modal-field-expiry input[name="expiration_date"]').hide();
_.bindAll(this, 'clicked');
},
- clicked: function (event) {
+ clicked: function(event) {
if (event.currentTarget.checked) {
this.show(this.$('#coupon_expiration_date'));
this.$el.find('#coupon_expiration_date').focus();
@@ -24,65 +24,65 @@ var edx = edx || {};
this.hide(this.$('#coupon_expiration_date'));
}
},
- show: function ($el) {
+ show: function($el) {
$el.css('display', 'inline');
},
- hide: function ($el) {
+ hide: function($el) {
$el.css('display', 'none');
}
});
$(function() {
- var $registration_code_status_form = $("form#set_regcode_status_form"),
+ var $registration_code_status_form = $('form#set_regcode_status_form'),
$lookup_button = $('#lookup_regcode', $registration_code_status_form),
$registration_code_status_form_error = $('#regcode_status_form_error', $registration_code_status_form),
$registration_code_status_form_success = $('#regcode_status_form_success', $registration_code_status_form);
- $( "#coupon_expiration_date" ).datepicker({
+ $('#coupon_expiration_date').datepicker({
minDate: 0
});
var view = new edx.instructor_dashboard.ecommerce.ExpiryCouponView();
- $('input[name="user-enrollment-report"]').click(function(){
+ $('input[name="user-enrollment-report"]').click(function() {
var url = $(this).data('endpoint');
$.ajax({
- type: 'POST',
- dataType: "json",
- url: url,
- success: function (data) {
- $('#enrollment-report-request-response').text(data['status']);
- return $("#enrollment-report-request-response").css({
- "display": "block"
- });
- },
- error: function(std_ajax_err) {
- $('#enrollment-report-request-response-error').text(gettext('There was a problem creating the report. Select "Create Executive Summary" to try again.'));
- return $("#enrollment-report-request-response-error").css({
- "display": "block"
- });
- }
- });
+ type: 'POST',
+ dataType: 'json',
+ url: url,
+ success: function(data) {
+ $('#enrollment-report-request-response').text(data['status']);
+ return $('#enrollment-report-request-response').css({
+ 'display': 'block'
+ });
+ },
+ error: function(std_ajax_err) {
+ $('#enrollment-report-request-response-error').text(gettext('There was a problem creating the report. Select "Create Executive Summary" to try again.'));
+ return $('#enrollment-report-request-response-error').css({
+ 'display': 'block'
+ });
+ }
+ });
});
- $('input[name="exec-summary-report"]').click(function(){
+ $('input[name="exec-summary-report"]').click(function() {
var url = $(this).data('endpoint');
$.ajax({
- type: 'POST',
- dataType: "json",
- url: url,
- success: function (data) {
- $("#exec-summary-report-request-response").text(data['status']);
- return $("#exec-summary-report-request-response").css({
- "display": "block"
- });
- },
- error: function(std_ajax_err) {
- $('#exec-summary-report-request-response-error').text(gettext('There was a problem creating the report. Select "Create Executive Summary" to try again.'));
- return $("#exec-summary-report-request-response-error").css({
- "display": "block"
- });
- }
- });
+ type: 'POST',
+ dataType: 'json',
+ url: url,
+ success: function(data) {
+ $('#exec-summary-report-request-response').text(data['status']);
+ return $('#exec-summary-report-request-response').css({
+ 'display': 'block'
+ });
+ },
+ error: function(std_ajax_err) {
+ $('#exec-summary-report-request-response-error').text(gettext('There was a problem creating the report. Select "Create Executive Summary" to try again.'));
+ return $('#exec-summary-report-request-response-error').css({
+ 'display': 'block'
+ });
+ }
+ });
});
- $lookup_button.click(function () {
+ $lookup_button.click(function() {
$registration_code_status_form_error.hide();
$lookup_button.attr('disabled', true);
var url = $(this).data('endpoint');
@@ -94,15 +94,15 @@ var edx = edx || {};
return false;
}
$.ajax({
- type: "GET",
+ type: 'GET',
data: {
- "registration_code" : lookup_registration_code
+ 'registration_code': lookup_registration_code
},
url: url,
- success: function (data) {
+ success: function(data) {
var is_registration_code_valid = data.is_registration_code_valid,
- is_registration_code_redeemed = data.is_registration_code_redeemed,
- is_registration_code_exists = data.is_registration_code_exists;
+ is_registration_code_redeemed = data.is_registration_code_redeemed,
+ is_registration_code_exists = data.is_registration_code_exists;
$lookup_button.removeAttr('disabled');
if (is_registration_code_exists == 'false') {
@@ -171,7 +171,7 @@ var edx = edx || {};
}
});
});
- $("section#invalidate_registration_code_modal").on('click', 'a.registration_code_action_link', function(event) {
+ $('section#invalidate_registration_code_modal').on('click', 'a.registration_code_action_link', function(event) {
event.preventDefault();
$registration_code_status_form_error.attr('style', 'display: none');
$lookup_button.attr('disabled', true);
@@ -179,13 +179,13 @@ var edx = edx || {};
var action_type = $(this).data('action-type');
var registration_code = $(this).data('registration-code');
$.ajax({
- type: "POST",
+ type: 'POST',
data: {
- "registration_code": registration_code,
- "action_type": action_type
+ 'registration_code': registration_code,
+ 'action_type': action_type
},
url: url,
- success: function (data) {
+ success: function(data) {
$('#set_regcode_status_form input[name="regcode_code"]').val('');
$registration_code_status_form.next().remove();
$registration_code_status_form_error.hide();
diff --git a/lms/static/js/instructor_dashboard/proctoring.js b/lms/static/js/instructor_dashboard/proctoring.js
index 5b0a2d49d1..1b886826da 100644
--- a/lms/static/js/instructor_dashboard/proctoring.js
+++ b/lms/static/js/instructor_dashboard/proctoring.js
@@ -1,22 +1,22 @@
$(function() {
var icons = {
- header: "ui-icon-carat-1-e",
- activeHeader: "ui-icon-carat-1-s"
+ header: 'ui-icon-carat-1-e',
+ activeHeader: 'ui-icon-carat-1-s'
};
- var proctoringAccordionPane = $("#proctoring-accordion");
+ var proctoringAccordionPane = $('#proctoring-accordion');
proctoringAccordionPane.accordion(
{
heightStyle: 'content',
- activate: function (event, ui) {
+ activate: function(event, ui) {
var active = proctoringAccordionPane.accordion('option', 'active');
$.cookie('saved_index', null);
$.cookie('saved_index', active);
},
animate: 400,
- header: "> .wrap > .hd",
- icons: icons,
- active: isNaN(parseInt($.cookie('saved_index'))) ? 0 : parseInt($.cookie('saved_index')),
- collapsible: true
+ header: '> .wrap > .hd',
+ icons: icons,
+ active: isNaN(parseInt($.cookie('saved_index'))) ? 0 : parseInt($.cookie('saved_index')),
+ collapsible: true
}
);
});
diff --git a/lms/static/js/learner_dashboard/collections/course_card_collection.js b/lms/static/js/learner_dashboard/collections/course_card_collection.js
index 998e0d33e8..d9d26dbb96 100644
--- a/lms/static/js/learner_dashboard/collections/course_card_collection.js
+++ b/lms/static/js/learner_dashboard/collections/course_card_collection.js
@@ -1,12 +1,12 @@
-(function (define) {
- 'use strict';
- define([
- 'backbone',
- 'js/learner_dashboard/models/course_card_model'
+(function(define) {
+ 'use strict';
+ define([
+ 'backbone',
+ 'js/learner_dashboard/models/course_card_model'
],
- function (Backbone, CourseCard) {
- return Backbone.Collection.extend({
- model: CourseCard
- });
- });
+ function(Backbone, CourseCard) {
+ return Backbone.Collection.extend({
+ model: CourseCard
+ });
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/collections/program_collection.js b/lms/static/js/learner_dashboard/collections/program_collection.js
index 47ca233e44..8644f40fb9 100644
--- a/lms/static/js/learner_dashboard/collections/program_collection.js
+++ b/lms/static/js/learner_dashboard/collections/program_collection.js
@@ -1,12 +1,12 @@
-(function (define) {
- 'use strict';
- define([
- 'backbone',
- 'js/learner_dashboard/models/program_model'
+(function(define) {
+ 'use strict';
+ define([
+ 'backbone',
+ 'js/learner_dashboard/models/program_model'
],
- function (Backbone, Program) {
- return Backbone.Collection.extend({
- model: Program
- });
- });
+ function(Backbone, Program) {
+ return Backbone.Collection.extend({
+ model: Program
+ });
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/collections/program_progress_collection.js b/lms/static/js/learner_dashboard/collections/program_progress_collection.js
index 562d58d7b9..bbf9bce290 100644
--- a/lms/static/js/learner_dashboard/collections/program_progress_collection.js
+++ b/lms/static/js/learner_dashboard/collections/program_progress_collection.js
@@ -1,9 +1,9 @@
-(function (define) {
- 'use strict';
- define([
- 'backbone'
+(function(define) {
+ 'use strict';
+ define([
+ 'backbone'
],
- function (Backbone) {
- return Backbone.Collection.extend({});
- });
+ function(Backbone) {
+ return Backbone.Collection.extend({});
+ });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/models/course_card_model.js b/lms/static/js/learner_dashboard/models/course_card_model.js
index 58e10527b3..0ed6ea78b1 100644
--- a/lms/static/js/learner_dashboard/models/course_card_model.js
+++ b/lms/static/js/learner_dashboard/models/course_card_model.js
@@ -1,105 +1,105 @@
/**
* Model for Course Programs.
*/
-(function (define) {
+(function(define) {
'use strict';
define([
- 'backbone'
- ],
- function (Backbone) {
- return Backbone.Model.extend({
- initialize: function(data) {
- if (data) {
- this.context = data;
- this.setActiveRunMode(this.getRunMode(data.run_modes));
- }
- },
-
- getUnselectedRunMode: function(runModes) {
- if(runModes && runModes.length > 0) {
- return {
- course_image_url: runModes[0].course_image_url,
- marketing_url: runModes[0].marketing_url,
- is_enrollment_open: runModes[0].is_enrollment_open
- };
- }
-
- return {};
- },
-
- getRunMode: function(runModes) {
- var enrolled_mode = _.findWhere(runModes, {is_enrolled: true}),
- openEnrollmentRunModes = this.getEnrollableRunModes(),
- desiredRunMode;
- // We populate our model by looking at the run modes.
- if (enrolled_mode) {
- // If the learner is already enrolled in a run mode, return that one.
- desiredRunMode = enrolled_mode;
- } else if (openEnrollmentRunModes.length > 0) {
- if (openEnrollmentRunModes.length === 1) {
- desiredRunMode = openEnrollmentRunModes[0];
- } else {
- desiredRunMode = this.getUnselectedRunMode(openEnrollmentRunModes);
+ 'backbone'
+ ],
+ function(Backbone) {
+ return Backbone.Model.extend({
+ initialize: function(data) {
+ if (data) {
+ this.context = data;
+ this.setActiveRunMode(this.getRunMode(data.run_modes));
}
- } else {
- desiredRunMode = this.getUnselectedRunMode(runModes);
- }
+ },
- return desiredRunMode;
- },
+ getUnselectedRunMode: function(runModes) {
+ if (runModes && runModes.length > 0) {
+ return {
+ course_image_url: runModes[0].course_image_url,
+ marketing_url: runModes[0].marketing_url,
+ is_enrollment_open: runModes[0].is_enrollment_open
+ };
+ }
- getEnrollableRunModes: function() {
- return _.where(this.context.run_modes, {
- is_enrollment_open: true,
- is_enrolled: false,
- is_course_ended: false
- });
- },
+ return {};
+ },
- getUpcomingRunModes: function() {
- return _.where(this.context.run_modes, {
- is_enrollment_open: false,
- is_enrolled: false,
- is_course_ended: false
- });
- },
+ getRunMode: function(runModes) {
+ var enrolled_mode = _.findWhere(runModes, {is_enrolled: true}),
+ openEnrollmentRunModes = this.getEnrollableRunModes(),
+ desiredRunMode;
+ // We populate our model by looking at the run modes.
+ if (enrolled_mode) {
+ // If the learner is already enrolled in a run mode, return that one.
+ desiredRunMode = enrolled_mode;
+ } else if (openEnrollmentRunModes.length > 0) {
+ if (openEnrollmentRunModes.length === 1) {
+ desiredRunMode = openEnrollmentRunModes[0];
+ } else {
+ desiredRunMode = this.getUnselectedRunMode(openEnrollmentRunModes);
+ }
+ } else {
+ desiredRunMode = this.getUnselectedRunMode(runModes);
+ }
- setActiveRunMode: function(runMode){
- if (runMode){
- this.set({
- certificate_url: runMode.certificate_url,
- course_image_url: runMode.course_image_url || '',
- course_key: runMode.course_key,
- course_url: runMode.course_url || '',
- display_name: this.context.display_name,
- end_date: runMode.end_date,
- enrollable_run_modes: this.getEnrollableRunModes(),
- is_course_ended: runMode.is_course_ended,
- is_enrolled: runMode.is_enrolled,
- is_enrollment_open: runMode.is_enrollment_open,
- key: this.context.key,
- marketing_url: runMode.marketing_url,
- mode_slug: runMode.mode_slug,
- run_key: runMode.run_key,
- start_date: runMode.start_date,
- upcoming_run_modes: this.getUpcomingRunModes(),
- upgrade_url: runMode.upgrade_url
+ return desiredRunMode;
+ },
+
+ getEnrollableRunModes: function() {
+ return _.where(this.context.run_modes, {
+ is_enrollment_open: true,
+ is_enrolled: false,
+ is_course_ended: false
});
- }
- },
+ },
- setUnselected: function() {
+ getUpcomingRunModes: function() {
+ return _.where(this.context.run_modes, {
+ is_enrollment_open: false,
+ is_enrolled: false,
+ is_course_ended: false
+ });
+ },
+
+ setActiveRunMode: function(runMode) {
+ if (runMode) {
+ this.set({
+ certificate_url: runMode.certificate_url,
+ course_image_url: runMode.course_image_url || '',
+ course_key: runMode.course_key,
+ course_url: runMode.course_url || '',
+ display_name: this.context.display_name,
+ end_date: runMode.end_date,
+ enrollable_run_modes: this.getEnrollableRunModes(),
+ is_course_ended: runMode.is_course_ended,
+ is_enrolled: runMode.is_enrolled,
+ is_enrollment_open: runMode.is_enrollment_open,
+ key: this.context.key,
+ marketing_url: runMode.marketing_url,
+ mode_slug: runMode.mode_slug,
+ run_key: runMode.run_key,
+ start_date: runMode.start_date,
+ upcoming_run_modes: this.getUpcomingRunModes(),
+ upgrade_url: runMode.upgrade_url
+ });
+ }
+ },
+
+ setUnselected: function() {
// Called to reset the model back to the unselected state.
- var unselectedMode = this.getUnselectedRunMode(this.get('enrollable_run_modes'));
- this.setActiveRunMode(unselectedMode);
- },
+ var unselectedMode = this.getUnselectedRunMode(this.get('enrollable_run_modes'));
+ this.setActiveRunMode(unselectedMode);
+ },
- updateRun: function(runKey){
- var selectedRun = _.findWhere(this.get('run_modes'), {run_key: runKey});
- if (selectedRun) {
- this.setActiveRunMode(selectedRun);
+ updateRun: function(runKey) {
+ var selectedRun = _.findWhere(this.get('run_modes'), {run_key: runKey});
+ if (selectedRun) {
+ this.setActiveRunMode(selectedRun);
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/models/course_enroll_model.js b/lms/static/js/learner_dashboard/models/course_enroll_model.js
index 1977eb9767..6eb58b03b0 100644
--- a/lms/static/js/learner_dashboard/models/course_enroll_model.js
+++ b/lms/static/js/learner_dashboard/models/course_enroll_model.js
@@ -1,13 +1,13 @@
/**
* Store data to enroll learners into the course
*/
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'backbone'
- ],
- function( Backbone) {
+ 'backbone'
+ ],
+ function(Backbone) {
return Backbone.Model.extend({
defaults: {
course_id: '',
diff --git a/lms/static/js/learner_dashboard/models/program_model.js b/lms/static/js/learner_dashboard/models/program_model.js
index c2743255f0..d5921daa6d 100644
--- a/lms/static/js/learner_dashboard/models/program_model.js
+++ b/lms/static/js/learner_dashboard/models/program_model.js
@@ -1,35 +1,35 @@
/**
* Model for Course Programs.
*/
-(function (define) {
+(function(define) {
'use strict';
define([
- 'backbone'
- ],
- function (Backbone) {
- return Backbone.Model.extend({
- initialize: function(data) {
- if (data){
- this.set({
- name: data.name,
- category: data.category,
- subtitle: data.subtitle,
- organizations: data.organizations,
- detailUrl: data.detail_url,
- smallBannerUrl: data.banner_image_urls.w348h116,
- mediumBannerUrl: data.banner_image_urls.w435h145,
- largeBannerUrl: data.banner_image_urls.w726h242,
- breakpoints: {
- max: {
- tiny: '320px',
- small: '540px',
- medium: '768px',
- large: '979px'
+ 'backbone'
+ ],
+ function(Backbone) {
+ return Backbone.Model.extend({
+ initialize: function(data) {
+ if (data) {
+ this.set({
+ name: data.name,
+ category: data.category,
+ subtitle: data.subtitle,
+ organizations: data.organizations,
+ detailUrl: data.detail_url,
+ smallBannerUrl: data.banner_image_urls.w348h116,
+ mediumBannerUrl: data.banner_image_urls.w435h145,
+ largeBannerUrl: data.banner_image_urls.w726h242,
+ breakpoints: {
+ max: {
+ tiny: '320px',
+ small: '540px',
+ medium: '768px',
+ large: '979px'
+ }
}
- }
- });
+ });
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/program_details_factory.js b/lms/static/js/learner_dashboard/program_details_factory.js
index af90d4ce6a..dea1494c9b 100644
--- a/lms/static/js/learner_dashboard/program_details_factory.js
+++ b/lms/static/js/learner_dashboard/program_details_factory.js
@@ -1,11 +1,11 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'js/learner_dashboard/views/program_details_view'
],
function(ProgramDetailsView) {
- return function (options) {
+ return function(options) {
var ProgramDetails = new ProgramDetailsView(options);
return ProgramDetails;
};
diff --git a/lms/static/js/learner_dashboard/program_list_factory.js b/lms/static/js/learner_dashboard/program_list_factory.js
index 217d6045fd..f5e3bb13ad 100644
--- a/lms/static/js/learner_dashboard/program_list_factory.js
+++ b/lms/static/js/learner_dashboard/program_list_factory.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
@@ -8,13 +8,13 @@
'js/learner_dashboard/collections/program_collection',
'js/learner_dashboard/collections/program_progress_collection'
],
- function (CollectionListView, SidebarView, ProgramCardView, ProgramCollection, ProgressCollection) {
- return function (options) {
+ function(CollectionListView, SidebarView, ProgramCardView, ProgramCollection, ProgressCollection) {
+ return function(options) {
var progressCollection = new ProgressCollection();
- if ( options.userProgress ) {
+ if (options.userProgress) {
progressCollection.set(options.userProgress);
- options.progressCollection = progressCollection;
+ options.progressCollection = progressCollection;
}
new CollectionListView({
@@ -28,7 +28,7 @@
}
}).render();
- if ( options.programsData.length ) {
+ if (options.programsData.length) {
new SidebarView({
el: '.sidebar',
context: options
diff --git a/lms/static/js/learner_dashboard/views/certificate_status_view.js b/lms/static/js/learner_dashboard/views/certificate_status_view.js
index a0678bb98d..a0680af0be 100644
--- a/lms/static/js/learner_dashboard/views/certificate_status_view.js
+++ b/lms/static/js/learner_dashboard/views/certificate_status_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
'jquery',
@@ -17,22 +17,22 @@
certificateStatusTpl,
certificateIconTpl
) {
- return Backbone.View.extend({
- statusTpl: HtmlUtils.template(certificateStatusTpl),
- iconTpl: HtmlUtils.template(certificateIconTpl),
+ return Backbone.View.extend({
+ statusTpl: HtmlUtils.template(certificateStatusTpl),
+ iconTpl: HtmlUtils.template(certificateIconTpl),
- initialize: function(options) {
- this.$el = options.$el;
- this.render();
- },
+ initialize: function(options) {
+ this.$el = options.$el;
+ this.render();
+ },
- render: function() {
- var data = this.model.toJSON();
+ render: function() {
+ var data = this.model.toJSON();
- data = $.extend(data, {certificateSvg: this.iconTpl()});
- HtmlUtils.setHtml(this.$el, this.statusTpl(data));
- }
- });
- }
+ data = $.extend(data, {certificateSvg: this.iconTpl()});
+ HtmlUtils.setHtml(this.$el, this.statusTpl(data));
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/certificate_view.js b/lms/static/js/learner_dashboard/views/certificate_view.js
index db823e0e07..6cb4ad3d36 100644
--- a/lms/static/js/learner_dashboard/views/certificate_view.js
+++ b/lms/static/js/learner_dashboard/views/certificate_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
'jquery',
@@ -13,27 +13,27 @@
gettext,
certificateTpl
) {
- return Backbone.View.extend({
- el: '.certificates-list',
- tpl: _.template(certificateTpl),
- initialize: function(data) {
- this.context = data.context;
- this.render();
- },
- render: function() {
- var certificatesData = this.context.certificatesData || [];
+ return Backbone.View.extend({
+ el: '.certificates-list',
+ tpl: _.template(certificateTpl),
+ initialize: function(data) {
+ this.context = data.context;
+ this.render();
+ },
+ render: function() {
+ var certificatesData = this.context.certificatesData || [];
- if (certificatesData.length) {
- this.$el.html(this.tpl(this.context));
- } else {
+ if (certificatesData.length) {
+ this.$el.html(this.tpl(this.context));
+ } else {
/**
* If not rendering remove el because
* styles are applied to it
*/
- this.remove();
- }
- }
- });
- }
+ this.remove();
+ }
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/collection_list_view.js b/lms/static/js/learner_dashboard/views/collection_list_view.js
index 1f902bb58b..f75553d978 100644
--- a/lms/static/js/learner_dashboard/views/collection_list_view.js
+++ b/lms/static/js/learner_dashboard/views/collection_list_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -9,7 +9,7 @@
'edx-ui-toolkit/js/utils/html-utils',
'text!../../../templates/learner_dashboard/empty_programs_list.underscore'
],
- function (Backbone,
+ function(Backbone,
$,
_,
gettext,
@@ -29,11 +29,11 @@
if (!this.collection.length) {
if (this.context.marketingUrl) {
- //Only show the advertising panel if the link is passed in
+ // Only show the advertising panel if the link is passed in
HtmlUtils.setHtml(this.$el, HtmlUtils.template(emptyProgramsListTpl)(this.context));
}
- } else {
- childList = [];
+ } else {
+ childList = [];
this.collection.each(function(model) {
var child = new this.childView({
@@ -43,7 +43,7 @@
childList.push(child.el);
}, this);
- if (this.titleContext){
+ if (this.titleContext) {
this.$el.before(HtmlUtils.ensureHtml(this.getTitleHtml()).toString());
}
@@ -51,9 +51,9 @@
}
},
- getTitleHtml: function(){
+ getTitleHtml: function() {
var titleHtml = HtmlUtils.joinHtml(
- HtmlUtils.HTML('<'),
+ HtmlUtils.HTML('<'),
this.titleContext.el,
HtmlUtils.HTML(' class="sr-only collection-title">'),
StringUtils.interpolate(this.titleContext.title),
diff --git a/lms/static/js/learner_dashboard/views/course_card_view.js b/lms/static/js/learner_dashboard/views/course_card_view.js
index 42bc2a6823..5acd0c9de0 100644
--- a/lms/static/js/learner_dashboard/views/course_card_view.js
+++ b/lms/static/js/learner_dashboard/views/course_card_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -24,59 +24,59 @@
CourseEnrollView,
pageTpl
) {
- return Backbone.View.extend({
- className: 'course-card card',
+ return Backbone.View.extend({
+ className: 'course-card card',
- tpl: HtmlUtils.template(pageTpl),
+ tpl: HtmlUtils.template(pageTpl),
- initialize: function(options) {
- this.enrollModel = new EnrollModel();
- if(options.context && options.context.urls){
- this.urlModel = new Backbone.Model(options.context.urls);
- this.enrollModel.urlRoot = this.urlModel.get('commerce_api_url');
- }
- this.render();
- this.listenTo(this.model, 'change', this.render);
- },
+ initialize: function(options) {
+ this.enrollModel = new EnrollModel();
+ if (options.context && options.context.urls) {
+ this.urlModel = new Backbone.Model(options.context.urls);
+ this.enrollModel.urlRoot = this.urlModel.get('commerce_api_url');
+ }
+ this.render();
+ this.listenTo(this.model, 'change', this.render);
+ },
- render: function() {
- var filledTemplate = this.tpl(this.model.toJSON());
- HtmlUtils.setHtml(this.$el, filledTemplate);
- this.postRender();
- },
+ render: function() {
+ var filledTemplate = this.tpl(this.model.toJSON());
+ HtmlUtils.setHtml(this.$el, filledTemplate);
+ this.postRender();
+ },
- postRender: function(){
- var $upgradeMessage = this.$('.upgrade-message'),
- $certStatus = this.$('.certificate-status');
+ postRender: function() {
+ var $upgradeMessage = this.$('.upgrade-message'),
+ $certStatus = this.$('.certificate-status');
- this.enrollView = new CourseEnrollView({
- $parentEl: this.$('.course-actions'),
- model: this.model,
- urlModel: this.urlModel,
- enrollModel: this.enrollModel
- });
+ this.enrollView = new CourseEnrollView({
+ $parentEl: this.$('.course-actions'),
+ model: this.model,
+ urlModel: this.urlModel,
+ enrollModel: this.enrollModel
+ });
- if ( this.model.get('upgrade_url') ) {
- this.upgradeMessage = new UpgradeMessageView({
- $el: $upgradeMessage,
- model: this.model
- });
+ if (this.model.get('upgrade_url')) {
+ this.upgradeMessage = new UpgradeMessageView({
+ $el: $upgradeMessage,
+ model: this.model
+ });
- $certStatus.remove();
- } else if ( this.model.get('certificate_url') ) {
- this.certificateStatus = new CertificateStatusView({
- $el: $certStatus,
- model: this.model
- });
+ $certStatus.remove();
+ } else if (this.model.get('certificate_url')) {
+ this.certificateStatus = new CertificateStatusView({
+ $el: $certStatus,
+ model: this.model
+ });
- $upgradeMessage.remove();
- } else {
+ $upgradeMessage.remove();
+ } else {
// Styles are applied to these elements which will be visible if they're empty.
- $upgradeMessage.remove();
- $certStatus.remove();
- }
- }
- });
- }
+ $upgradeMessage.remove();
+ $certStatus.remove();
+ }
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/course_enroll_view.js b/lms/static/js/learner_dashboard/views/course_enroll_view.js
index 2e56ca6306..f8d45bbee2 100644
--- a/lms/static/js/learner_dashboard/views/course_enroll_view.js
+++ b/lms/static/js/learner_dashboard/views/course_enroll_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -16,97 +16,96 @@
HtmlUtils,
pageTpl
) {
- return Backbone.View.extend({
- tpl: HtmlUtils.template(pageTpl),
+ return Backbone.View.extend({
+ tpl: HtmlUtils.template(pageTpl),
- events: {
- 'click .enroll-button': 'handleEnroll',
- 'change .run-select': 'handleRunSelect',
- },
+ events: {
+ 'click .enroll-button': 'handleEnroll',
+ 'change .run-select': 'handleRunSelect'
+ },
- initialize: function(options) {
- this.$parentEl = options.$parentEl;
- this.enrollModel = options.enrollModel;
- this.urlModel = options.urlModel;
- this.render();
- if (this.urlModel){
- this.trackSelectionUrl = this.urlModel.get('track_selection_url');
- }
- },
+ initialize: function(options) {
+ this.$parentEl = options.$parentEl;
+ this.enrollModel = options.enrollModel;
+ this.urlModel = options.urlModel;
+ this.render();
+ if (this.urlModel) {
+ this.trackSelectionUrl = this.urlModel.get('track_selection_url');
+ }
+ },
- render: function() {
- var filledTemplate;
- if (this.$parentEl && this.enrollModel){
- filledTemplate = this.tpl(this.model.toJSON());
- HtmlUtils.setHtml(this.$el, filledTemplate);
- HtmlUtils.setHtml(this.$parentEl, HtmlUtils.HTML(this.$el));
- }
- },
+ render: function() {
+ var filledTemplate;
+ if (this.$parentEl && this.enrollModel) {
+ filledTemplate = this.tpl(this.model.toJSON());
+ HtmlUtils.setHtml(this.$el, filledTemplate);
+ HtmlUtils.setHtml(this.$parentEl, HtmlUtils.HTML(this.$el));
+ }
+ },
- handleEnroll: function(){
- //Enrollment click event handled here
- if (!this.model.get('course_key')){
- this.$('.select-error').css('visibility','visible');
- } else if (!this.model.get('is_enrolled')){
+ handleEnroll: function() {
+ // Enrollment click event handled here
+ if (!this.model.get('course_key')) {
+ this.$('.select-error').css('visibility', 'visible');
+ } else if (!this.model.get('is_enrolled')) {
// actually enroll
- this.enrollModel.save({
- course_id: this.model.get('course_key')
- }, {
- success: _.bind(this.enrollSuccess, this),
- error: _.bind(this.enrollError, this)
- });
- }
- },
+ this.enrollModel.save({
+ course_id: this.model.get('course_key')
+ }, {
+ success: _.bind(this.enrollSuccess, this),
+ error: _.bind(this.enrollError, this)
+ });
+ }
+ },
- handleRunSelect: function(event){
- var runKey;
- if (event.target){
- runKey = $(event.target).val();
- if (runKey){
- this.model.updateRun(runKey);
- } else {
- //Set back the unselected states
- this.model.setUnselected();
- }
- }
- },
+ handleRunSelect: function(event) {
+ var runKey;
+ if (event.target) {
+ runKey = $(event.target).val();
+ if (runKey) {
+ this.model.updateRun(runKey);
+ } else {
+ // Set back the unselected states
+ this.model.setUnselected();
+ }
+ }
+ },
- enrollSuccess: function(){
- var courseKey = this.model.get('course_key');
- if (this.trackSelectionUrl) {
+ enrollSuccess: function() {
+ var courseKey = this.model.get('course_key');
+ if (this.trackSelectionUrl) {
// Go to track selection page
- this.redirect( this.trackSelectionUrl + courseKey );
- } else {
- this.model.set({
- is_enrolled: true
- });
- }
- },
+ this.redirect(this.trackSelectionUrl + courseKey);
+ } else {
+ this.model.set({
+ is_enrolled: true
+ });
+ }
+ },
- enrollError: function(model, response) {
-
- if (response.status === 403 && response.responseJSON.user_message_url) {
+ enrollError: function(model, response) {
+ if (response.status === 403 && response.responseJSON.user_message_url) {
/**
* Check if we've been blocked from the course
* because of country access rules.
* If so, redirect to a page explaining to the user
* why they were blocked.
*/
- this.redirect( response.responseJSON.user_message_url );
- } else if (this.trackSelectionUrl){
+ this.redirect(response.responseJSON.user_message_url);
+ } else if (this.trackSelectionUrl) {
/**
* Otherwise, go to the track selection page as usual.
* This can occur, for example, when a course does not
* have a free enrollment mode, so we can't auto-enroll.
*/
- this.redirect( this.trackSelectionUrl + this.model.get('course_key') );
- }
- },
+ this.redirect(this.trackSelectionUrl + this.model.get('course_key'));
+ }
+ },
- redirect: function( url ) {
- window.location.href = url;
- }
- });
- }
+ redirect: function(url) {
+ window.location.href = url;
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/explore_new_programs_view.js b/lms/static/js/learner_dashboard/views/explore_new_programs_view.js
index 4ebe746ed1..c7fea9b7f8 100644
--- a/lms/static/js/learner_dashboard/views/explore_new_programs_view.js
+++ b/lms/static/js/learner_dashboard/views/explore_new_programs_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -14,31 +14,31 @@
gettext,
exploreTpl
) {
- return Backbone.View.extend({
- el: '.program-advertise',
+ return Backbone.View.extend({
+ el: '.program-advertise',
- tpl: _.template(exploreTpl),
+ tpl: _.template(exploreTpl),
- initialize: function(data) {
- this.context = data.context;
- this.$parentEl = $(this.parentEl);
+ initialize: function(data) {
+ this.context = data.context;
+ this.$parentEl = $(this.parentEl);
- if (this.context.marketingUrl){
+ if (this.context.marketingUrl) {
// Only render if there is a link
- this.render();
- } else {
+ this.render();
+ } else {
/**
* If not rendering remove el because
* styles are applied to it
*/
- this.remove();
- }
- },
+ this.remove();
+ }
+ },
- render: function() {
- this.$el.html(this.tpl(this.context));
- }
- });
- }
+ render: function() {
+ this.$el.html(this.tpl(this.context));
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/program_card_view.js b/lms/static/js/learner_dashboard/views/program_card_view.js
index 761cd705ce..bbbf9209e0 100644
--- a/lms/static/js/learner_dashboard/views/program_card_view.js
+++ b/lms/static/js/learner_dashboard/views/program_card_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -16,110 +16,110 @@
programCardTpl,
picturefill
) {
- return Backbone.View.extend({
+ return Backbone.View.extend({
- className: 'program-card',
+ className: 'program-card',
- attributes: function() {
- return {
- 'aria-labelledby': 'program-' + this.model.get('id'),
- 'role': 'group'
- };
- },
+ attributes: function() {
+ return {
+ 'aria-labelledby': 'program-' + this.model.get('id'),
+ 'role': 'group'
+ };
+ },
- tpl: _.template(programCardTpl),
+ tpl: _.template(programCardTpl),
- initialize: function(data) {
- this.progressCollection = data.context.progressCollection;
- if ( this.progressCollection ) {
- this.progressModel = this.progressCollection.findWhere({
- id: this.model.get('id')
- });
- }
- this.render();
- },
+ initialize: function(data) {
+ this.progressCollection = data.context.progressCollection;
+ if (this.progressCollection) {
+ this.progressModel = this.progressCollection.findWhere({
+ id: this.model.get('id')
+ });
+ }
+ this.render();
+ },
- render: function() {
- var orgList = _.map(this.model.get('organizations'), function(org) {
- return gettext(org.key);
- }),
- data = $.extend(
+ render: function() {
+ var orgList = _.map(this.model.get('organizations'), function(org) {
+ return gettext(org.key);
+ }),
+ data = $.extend(
this.model.toJSON(),
this.getProgramProgress(),
{orgList: orgList.join(' ')}
);
- this.$el.html(this.tpl(data));
- this.postRender();
- },
+ this.$el.html(this.tpl(data));
+ this.postRender();
+ },
- postRender: function() {
+ postRender: function() {
// Add describedby to parent only if progess is present
- if ( this.progressModel ) {
- this.$el.attr('aria-describedby', 'status-' + this.model.get('id'));
- }
+ if (this.progressModel) {
+ this.$el.attr('aria-describedby', 'status-' + this.model.get('id'));
+ }
- if(navigator.userAgent.indexOf('MSIE') !== -1 ||
- navigator.appVersion.indexOf('Trident/') > 0){
+ if (navigator.userAgent.indexOf('MSIE') !== -1 ||
+ navigator.appVersion.indexOf('Trident/') > 0) {
/* Microsoft Internet Explorer detected in. */
- window.setTimeout( function() {
- this.reLoadBannerImage();
- }.bind(this), 100);
- }
- },
+ window.setTimeout(function() {
+ this.reLoadBannerImage();
+ }.bind(this), 100);
+ }
+ },
// Calculate counts for progress and percentages for styling
- getProgramProgress: function() {
- var progress = this.progressModel ? this.progressModel.toJSON() : false;
-
- if ( progress) {
- progress.total = {
- completed: progress.completed.length,
- in_progress: progress.in_progress.length,
- not_started: progress.not_started.length
- };
+ getProgramProgress: function() {
+ var progress = this.progressModel ? this.progressModel.toJSON() : false;
- progress.total.courses = progress.total.completed +
+ if (progress) {
+ progress.total = {
+ completed: progress.completed.length,
+ in_progress: progress.in_progress.length,
+ not_started: progress.not_started.length
+ };
+
+ progress.total.courses = progress.total.completed +
progress.total.in_progress +
progress.total.not_started;
- progress.percentage = {
- completed: this.getWidth(progress.total.completed, progress.total.courses),
- in_progress: this.getWidth(progress.total.in_progress, progress.total.courses)
- };
- }
+ progress.percentage = {
+ completed: this.getWidth(progress.total.completed, progress.total.courses),
+ in_progress: this.getWidth(progress.total.in_progress, progress.total.courses)
+ };
+ }
- return {
- progress: progress
- };
- },
+ return {
+ progress: progress
+ };
+ },
- getWidth: function(val, total) {
- var int = ( val / total ) * 100;
-
- return int + '%';
- },
+ getWidth: function(val, total) {
+ var int = (val / total) * 100;
+
+ return int + '%';
+ },
// Defer loading the rest of the page to limit FOUC
- reLoadBannerImage: function() {
- var $img = this.$('.program_card .banner-image'),
- imgSrcAttr = $img ? $img.attr('src') : {};
-
- if (!imgSrcAttr || imgSrcAttr.length < 0) {
- try{
- this.reEvaluatePicture();
- }catch(err){
- //Swallow the error here
- }
- }
- },
+ reLoadBannerImage: function() {
+ var $img = this.$('.program_card .banner-image'),
+ imgSrcAttr = $img ? $img.attr('src') : {};
- reEvaluatePicture: function(){
- picturefill({
- reevaluate: true
- });
- }
- });
- }
+ if (!imgSrcAttr || imgSrcAttr.length < 0) {
+ try {
+ this.reEvaluatePicture();
+ } catch (err) {
+ // Swallow the error here
+ }
+ }
+ },
+
+ reEvaluatePicture: function() {
+ picturefill({
+ reevaluate: true
+ });
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/program_details_view.js b/lms/static/js/learner_dashboard/views/program_details_view.js
index 06e53c3ae1..74effe5a08 100644
--- a/lms/static/js/learner_dashboard/views/program_details_view.js
+++ b/lms/static/js/learner_dashboard/views/program_details_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -24,41 +24,41 @@
CourseCardView,
pageTpl
) {
- return Backbone.View.extend({
- el: '.js-program-details-wrapper',
+ return Backbone.View.extend({
+ el: '.js-program-details-wrapper',
- tpl: HtmlUtils.template(pageTpl),
+ tpl: HtmlUtils.template(pageTpl),
- initialize: function(options) {
- this.options = options;
- this.programModel = new Backbone.Model(this.options.programData);
- this.courseCardCollection = new CourseCardCollection(
+ initialize: function(options) {
+ this.options = options;
+ this.programModel = new Backbone.Model(this.options.programData);
+ this.courseCardCollection = new CourseCardCollection(
this.programModel.get('course_codes')
);
- this.render();
- },
+ this.render();
+ },
- render: function() {
- HtmlUtils.setHtml(this.$el, this.tpl());
- this.postRender();
- },
+ render: function() {
+ HtmlUtils.setHtml(this.$el, this.tpl());
+ this.postRender();
+ },
- postRender: function() {
- this.headerView = new HeaderView({
- model: new Backbone.Model(this.options)
- });
- new CollectionListView({
- el: '.js-course-list',
- childView: CourseCardView,
- collection: this.courseCardCollection,
- context: this.options,
- titleContext: {
- el: 'h2',
- title: 'Course List'
- }
- }).render();
- }
- });
- }
+ postRender: function() {
+ this.headerView = new HeaderView({
+ model: new Backbone.Model(this.options)
+ });
+ new CollectionListView({
+ el: '.js-course-list',
+ childView: CourseCardView,
+ collection: this.courseCardCollection,
+ context: this.options,
+ titleContext: {
+ el: 'h2',
+ title: 'Course List'
+ }
+ }).render();
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/program_header_view.js b/lms/static/js/learner_dashboard/views/program_header_view.js
index 20380c73b9..b0f0933533 100644
--- a/lms/static/js/learner_dashboard/views/program_header_view.js
+++ b/lms/static/js/learner_dashboard/views/program_header_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -8,50 +8,50 @@
'picturefill'
],
function(Backbone, $, HtmlUtils, pageTpl, picturefill) {
- return Backbone.View.extend({
- breakpoints: {
- min: {
- 'medium': '768px',
- 'large': '1180px'
- }
- },
+ return Backbone.View.extend({
+ breakpoints: {
+ min: {
+ 'medium': '768px',
+ 'large': '1180px'
+ }
+ },
- el: '.js-program-header',
+ el: '.js-program-header',
- tpl: HtmlUtils.template(pageTpl),
+ tpl: HtmlUtils.template(pageTpl),
- initialize: function() {
- this.render();
- },
+ initialize: function() {
+ this.render();
+ },
- render: function() {
- var data = $.extend(this.model.toJSON(), {
- breakpoints: this.breakpoints
- });
+ render: function() {
+ var data = $.extend(this.model.toJSON(), {
+ breakpoints: this.breakpoints
+ });
- if ( this.model.get('programData') ) {
- HtmlUtils.setHtml(this.$el, this.tpl(data));
- this.postRender();
- }
- },
+ if (this.model.get('programData')) {
+ HtmlUtils.setHtml(this.$el, this.tpl(data));
+ this.postRender();
+ }
+ },
- postRender: function() {
+ postRender: function() {
// To resolve a bug in IE with picturefill reevaluate images
- if (navigator.userAgent.indexOf('MSIE') !== -1 ||
- navigator.appVersion.indexOf('Trident/') > 0){
+ if (navigator.userAgent.indexOf('MSIE') !== -1 ||
+ navigator.appVersion.indexOf('Trident/') > 0) {
/* Microsoft Internet Explorer detected in. */
- window.setTimeout( function() {
- this.reEvaluatePicture();
- }.bind(this), 100);
- }
- },
+ window.setTimeout(function() {
+ this.reEvaluatePicture();
+ }.bind(this), 100);
+ }
+ },
- reEvaluatePicture: function(){
- picturefill({
- reevaluate: true
- });
- }
- });
- }
+ reEvaluatePicture: function() {
+ picturefill({
+ reevaluate: true
+ });
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/sidebar_view.js b/lms/static/js/learner_dashboard/views/sidebar_view.js
index e2c9502556..c7bd481dbc 100644
--- a/lms/static/js/learner_dashboard/views/sidebar_view.js
+++ b/lms/static/js/learner_dashboard/views/sidebar_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
@@ -18,30 +18,30 @@
CertificateView,
sidebarTpl
) {
- return Backbone.View.extend({
- el: '.sidebar',
+ return Backbone.View.extend({
+ el: '.sidebar',
- tpl: _.template(sidebarTpl),
+ tpl: _.template(sidebarTpl),
- initialize: function(data) {
- this.context = data.context;
- },
+ initialize: function(data) {
+ this.context = data.context;
+ },
- render: function() {
- this.$el.html(this.tpl(this.context));
- this.postRender();
- },
+ render: function() {
+ this.$el.html(this.tpl(this.context));
+ this.postRender();
+ },
- postRender: function() {
- this.newProgramsView = new NewProgramsView({
- context: this.context
- });
+ postRender: function() {
+ this.newProgramsView = new NewProgramsView({
+ context: this.context
+ });
- this.newCertificateView = new CertificateView({
- context: this.context
- });
- }
- });
- }
+ this.newCertificateView = new CertificateView({
+ context: this.context
+ });
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/learner_dashboard/views/upgrade_message_view.js b/lms/static/js/learner_dashboard/views/upgrade_message_view.js
index 3928c37aef..5f6012374d 100644
--- a/lms/static/js/learner_dashboard/views/upgrade_message_view.js
+++ b/lms/static/js/learner_dashboard/views/upgrade_message_view.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone',
'jquery',
@@ -17,22 +17,22 @@
upgradeMessageTpl,
certificateIconTpl
) {
- return Backbone.View.extend({
- messageTpl: HtmlUtils.template(upgradeMessageTpl),
- iconTpl: HtmlUtils.template(certificateIconTpl),
+ return Backbone.View.extend({
+ messageTpl: HtmlUtils.template(upgradeMessageTpl),
+ iconTpl: HtmlUtils.template(certificateIconTpl),
- initialize: function(options) {
- this.$el = options.$el;
- this.render();
- },
+ initialize: function(options) {
+ this.$el = options.$el;
+ this.render();
+ },
- render: function() {
- var data = this.model.toJSON();
+ render: function() {
+ var data = this.model.toJSON();
- data = $.extend(data, {certificateSvg: this.iconTpl()});
- HtmlUtils.setHtml(this.$el, this.messageTpl(data));
- }
- });
- }
+ data = $.extend(data, {certificateSvg: this.iconTpl()});
+ HtmlUtils.setHtml(this.$el, this.messageTpl(data));
+ }
+ });
+ }
);
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/logout.js b/lms/static/js/logout.js
index c2db7a30f7..48bfac8853 100644
--- a/lms/static/js/logout.js
+++ b/lms/static/js/logout.js
@@ -4,10 +4,10 @@
* This script waits for all iframes on the page to load before redirecting the user
* to a specified URL. If there are no iframes on the page, the user is immediately redirected.
*/
-(function ($) {
+(function($) {
'use strict';
- $(function () {
+ $(function() {
var $iframeContainer = $('#iframeContainer'),
$iframes = $iframeContainer.find('iframe'),
redirectUrl = $iframeContainer.data('redirect-url');
@@ -16,7 +16,7 @@
window.location = redirectUrl;
}
- $iframes.allLoaded(function () {
+ $iframes.allLoaded(function() {
window.location = redirectUrl;
});
});
diff --git a/lms/static/js/models/notification.js b/lms/static/js/models/notification.js
index d256ef1803..0bcd2a0fda 100644
--- a/lms/static/js/models/notification.js
+++ b/lms/static/js/models/notification.js
@@ -5,17 +5,17 @@
* The type of notification to be shown.
* Supported types are "confirmation", "warning" and "error".
*/
- type: "confirmation",
+ type: 'confirmation',
/**
* The title to be shown for the notification. This string should be short so
* that it can be shown on a single line.
*/
- title: "",
+ title: '',
/**
* An optional message giving more details for the notification. This string can be as long
* as needed and will wrap.
*/
- message: "",
+ message: '',
/**
* An optional array of detail messages to be shown beneath the title and message. This is
* typically used to enumerate a set of warning or error conditions that occurred.
@@ -29,11 +29,11 @@
* The class to be added to the action button. This allows selectors to be written that can
* target the action button directly.
*/
- actionClass: "",
+ actionClass: '',
/**
* An optional icon class to be shown before the text on the action button.
*/
- actionIconClass: "",
+ actionIconClass: '',
/**
* An optional callback that will be invoked when the user clicks on the action button.
*/
diff --git a/lms/static/js/my_courses_dropdown.js b/lms/static/js/my_courses_dropdown.js
index 516e268f52..88d6861f5f 100644
--- a/lms/static/js/my_courses_dropdown.js
+++ b/lms/static/js/my_courses_dropdown.js
@@ -1,81 +1,81 @@
-$(document).ready(function () {
- 'use strict';
+$(document).ready(function() {
+ 'use strict';
// define variables for code legibility
- var dropdownMenuToggle = $('.dropdown');
- var dropdownMenu = $('.dropdown-menu');
- var menuItems = dropdownMenu.find('a');
+ var dropdownMenuToggle = $('.dropdown');
+ var dropdownMenu = $('.dropdown-menu');
+ var menuItems = dropdownMenu.find('a');
// bind menu toggle click for later use
- dropdownMenuToggle.toggle(function() {
- dropdownMenu.addClass("expanded").find('a').first().focus();
- dropdownMenuToggle.addClass("active").attr("aria-expanded", "true");
- }, function() {
- dropdownMenu.removeClass("expanded");
- dropdownMenuToggle.removeClass("active").attr("aria-expanded", "false").focus();
- });
+ dropdownMenuToggle.toggle(function() {
+ dropdownMenu.addClass('expanded').find('a').first().focus();
+ dropdownMenuToggle.addClass('active').attr('aria-expanded', 'true');
+ }, function() {
+ dropdownMenu.removeClass('expanded');
+ dropdownMenuToggle.removeClass('active').attr('aria-expanded', 'false').focus();
+ });
- //catch keypresses when focused on dropdownMenuToggle (we only care about spacebar keypresses here)
- dropdownMenuToggle.on('keydown', function(event){
+ // catch keypresses when focused on dropdownMenuToggle (we only care about spacebar keypresses here)
+ dropdownMenuToggle.on('keydown', function(event) {
// if space key pressed
- if ( event.which == 32) {
- dropdownMenuToggle.click();
- event.preventDefault();
- }
- });
+ if (event.which == 32) {
+ dropdownMenuToggle.click();
+ event.preventDefault();
+ }
+ });
- //catch keypresses when inside dropdownMenu (we want to catch spacebar; escape; up arrow or shift+tab; and down arrow or tab)
- dropdownMenu.on('keydown', function(event){
- catchKeyPress($(this), event);
- });
+ // catch keypresses when inside dropdownMenu (we want to catch spacebar; escape; up arrow or shift+tab; and down arrow or tab)
+ dropdownMenu.on('keydown', function(event) {
+ catchKeyPress($(this), event);
+ });
- function catchKeyPress(object, event) {
+ function catchKeyPress(object, event) {
// get currently focused item
- var focusedItem = jQuery(':focus');
+ var focusedItem = jQuery(':focus');
// get the number of focusable items
- var numberOfMenuItems = menuItems.length
+ var numberOfMenuItems = menuItems.length;
// get the index of the currently focused item
- var focusedItemIndex = menuItems.index(focusedItem);
+ var focusedItemIndex = menuItems.index(focusedItem);
// var to store next focused item index
- var itemToFocusIndex;
+ var itemToFocusIndex;
// if space key pressed
- if ( event.which == 32) {
- dropdownMenuToggle.click();
- event.preventDefault();
- }
+ if (event.which == 32) {
+ dropdownMenuToggle.click();
+ event.preventDefault();
+ }
// if escape key pressed
- if (event.which == 27) {
- dropdownMenuToggle.click();
- event.preventDefault();
- }
+ if (event.which == 27) {
+ dropdownMenuToggle.click();
+ event.preventDefault();
+ }
// if up arrow key pressed or shift+tab
- if (event.which == 38 || (event.which == 9 && event.shiftKey)) {
+ if (event.which == 38 || (event.which == 9 && event.shiftKey)) {
// if first item go to last
- if (focusedItemIndex === 0) {
- menuItems.last().focus();
- } else {
- itemToFocusIndex = focusedItemIndex - 1;
- menuItems.get(itemToFocusIndex).focus();
- }
- event.preventDefault();
- }
+ if (focusedItemIndex === 0) {
+ menuItems.last().focus();
+ } else {
+ itemToFocusIndex = focusedItemIndex - 1;
+ menuItems.get(itemToFocusIndex).focus();
+ }
+ event.preventDefault();
+ }
// if down arrow key pressed or tab key
- if (event.which == 40 || event.which == 9) {
+ if (event.which == 40 || event.which == 9) {
// if last item go to first
- if (focusedItemIndex == numberOfMenuItems - 1) {
- menuItems.first().focus();
- } else {
- itemToFocusIndex = focusedItemIndex + 1;
- menuItems.get(itemToFocusIndex).focus();
- }
- event.preventDefault();
+ if (focusedItemIndex == numberOfMenuItems - 1) {
+ menuItems.first().focus();
+ } else {
+ itemToFocusIndex = focusedItemIndex + 1;
+ menuItems.get(itemToFocusIndex).focus();
+ }
+ event.preventDefault();
+ }
}
- }
});
diff --git a/lms/static/js/pdf-analytics.js b/lms/static/js/pdf-analytics.js
index 0d3805bd30..636ff2108d 100644
--- a/lms/static/js/pdf-analytics.js
+++ b/lms/static/js/pdf-analytics.js
@@ -1,102 +1,102 @@
function sendLog(name, data, event_type) {
- var message = data || {};
- message.chapter = PDF_URL || '';
- message.name = "textbook.pdf." + name;
- Logger.log(event_type ? event_type : message.name, message);
-};
+ var message = data || {};
+ message.chapter = PDF_URL || '';
+ message.name = 'textbook.pdf.' + name;
+ Logger.log(event_type ? event_type : message.name, message);
+}
// this event is loaded after the others to accurately represent the order of events:
// click next -> pagechange
$(function() {
- var first_page = true;
- var scroll = {timeStamp: 0, direction: null};
+ var first_page = true;
+ var scroll = {timeStamp: 0, direction: null};
- $(window).bind("pagechange", function(event) {
+ $(window).bind('pagechange', function(event) {
// log every page render
- var page = PDFViewerApplication.page;
- var old_page = event.originalEvent.previousPageNumber;
+ var page = PDFViewerApplication.page;
+ var old_page = event.originalEvent.previousPageNumber;
// pagechange is called many times per viewing.
- if (old_page !== page || first_page) {
- first_page = false;
- if ((event.timeStamp - scroll.timeStamp) < 50) {
- sendLog("page.scrolled", {"page": page, "direction": scroll.direction});
- }
- sendLog("page.loaded", {"type": "gotopage", "old": old_page, "new": page}, "book");
- scroll.timeStamp = 0;
- }
- });
+ if (old_page !== page || first_page) {
+ first_page = false;
+ if ((event.timeStamp - scroll.timeStamp) < 50) {
+ sendLog('page.scrolled', {'page': page, 'direction': scroll.direction});
+ }
+ sendLog('page.loaded', {'type': 'gotopage', 'old': old_page, 'new': page}, 'book');
+ scroll.timeStamp = 0;
+ }
+ });
- $('#viewerContainer').bind('DOMMouseScroll mousewheel', function(event) {
- scroll.timeStamp = event.timeStamp;
- scroll.direction = PDFViewerApplication.pdfViewer.scroll.down ? "down" : "up";
- });
+ $('#viewerContainer').bind('DOMMouseScroll mousewheel', function(event) {
+ scroll.timeStamp = event.timeStamp;
+ scroll.direction = PDFViewerApplication.pdfViewer.scroll.down ? 'down' : 'up';
+ });
});
$('#viewThumbnail,#sidebarToggle').on('click', function() {
- sendLog("thumbnails.toggled", {"page": PDFViewerApplication.page});
- });
+ sendLog('thumbnails.toggled', {'page': PDFViewerApplication.page});
+});
-$('#thumbnailView a').live('click', function(){
- sendLog("thumbnail.navigated", {"page": $('#thumbnailView a').index(this) + 1, "thumbnail_title": $(this).attr('title')});
+$('#thumbnailView a').live('click', function() {
+ sendLog('thumbnail.navigated', {'page': $('#thumbnailView a').index(this) + 1, 'thumbnail_title': $(this).attr('title')});
});
$('#viewOutline').on('click', function() {
- sendLog("outline.toggled", {"page": PDFViewerApplication.page});
- });
+ sendLog('outline.toggled', {'page': PDFViewerApplication.page});
+});
$('#previous').on('click', function() {
- sendLog("page.navigatednext", {"type": "prevpage", "new": PDFViewerApplication.page - 1}, "book");
- });
+ sendLog('page.navigatednext', {'type': 'prevpage', 'new': PDFViewerApplication.page - 1}, 'book');
+});
$('#next').on('click', function() {
- sendLog("page.navigatednext", {"type": "nextpage", "new": PDFViewerApplication.page + 1}, "book");
- });
+ sendLog('page.navigatednext', {'type': 'nextpage', 'new': PDFViewerApplication.page + 1}, 'book');
+});
$('#zoomIn,#zoomOut').on('click', function() {
- sendLog("zoom.buttons.changed", {"direction": $(this).attr("id") == "zoomIn" ? "in" : "out", "page": PDFViewerApplication.page});
- });
+ sendLog('zoom.buttons.changed', {'direction': $(this).attr('id') == 'zoomIn' ? 'in' : 'out', 'page': PDFViewerApplication.page});
+});
$('#pageNumber').on('change', function() {
- sendLog("page.navigated", {"page": $(this).val()});
- });
+ sendLog('page.navigated', {'page': $(this).val()});
+});
var old_amount = 1;
$(window).bind('scalechange', function(event) {
- var amount = event.originalEvent.scale;
- if (amount !== old_amount) {
- sendLog("display.scaled", {"amount": amount, "page": PDFViewerApplication.page});
- old_amount = amount;
- }
+ var amount = event.originalEvent.scale;
+ if (amount !== old_amount) {
+ sendLog('display.scaled', {'amount': amount, 'page': PDFViewerApplication.page});
+ old_amount = amount;
+ }
});
$('#scaleSelect').on('change', function() {
- sendLog("zoom.menu.changed", {"amount": $("#scaleSelect").val(), "page": PDFViewerApplication.page});
+ sendLog('zoom.menu.changed', {'amount': $('#scaleSelect').val(), 'page': PDFViewerApplication.page});
});
var search_event = null;
-$(window).bind("find findhighlightallchange findagain findcasesensitivitychange", function(event) {
- if (search_event && event.type == 'find') {
- clearTimeout(search_event);
- }
- search_event = setTimeout(function(){
- var message = event.originalEvent.detail;
- message.status = $('#findMsg').text();
- message.page = PDFViewerApplication.page;
- var event_name = "search";
- switch (event.type) {
- case "find":
- event_name += ".executed";
- break;
- case "findhighlightallchange":
- event_name += ".highlight.toggled";
- break;
- case "findagain":
- event_name += ".navigatednext";
- break;
- case "findcasesensitivitychange":
- event_name += "casesensitivity.toggled";
- break;
+$(window).bind('find findhighlightallchange findagain findcasesensitivitychange', function(event) {
+ if (search_event && event.type == 'find') {
+ clearTimeout(search_event);
}
- sendLog(event_name, message);
- }, 500);
+ search_event = setTimeout(function() {
+ var message = event.originalEvent.detail;
+ message.status = $('#findMsg').text();
+ message.page = PDFViewerApplication.page;
+ var event_name = 'search';
+ switch (event.type) {
+ case 'find':
+ event_name += '.executed';
+ break;
+ case 'findhighlightallchange':
+ event_name += '.highlight.toggled';
+ break;
+ case 'findagain':
+ event_name += '.navigatednext';
+ break;
+ case 'findcasesensitivitychange':
+ event_name += 'casesensitivity.toggled';
+ break;
+ }
+ sendLog(event_name, message);
+ }, 500);
});
diff --git a/lms/static/js/pending_tasks.js b/lms/static/js/pending_tasks.js
index ebeb896efa..69fb20ce43 100644
--- a/lms/static/js/pending_tasks.js
+++ b/lms/static/js/pending_tasks.js
@@ -7,16 +7,14 @@
// it is not included in any further polling.
(function() {
-
- var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
+ var __bind = function(fn, me) { return function() { return fn.apply(me, arguments); }; };
this.InstructorTaskProgress = (function() {
-
function InstructorTaskProgress(element) {
this.update_progress = __bind(this.update_progress, this);
this.get_status = __bind(this.get_status, this);
this.element = element;
- this.entries = $(element).find('.task-progress-entry')
+ this.entries = $(element).find('.task-progress-entry');
if (window.queuePollerID) {
window.clearTimeout(window.queuePollerID);
}
@@ -38,9 +36,9 @@
var task_dict = response[task_id];
// find the corresponding entry, and update it:
entry = $(_this.element).find('[data-task-id="' + task_id + '"]');
- entry.find('.task-state').text(task_dict.task_state)
+ entry.find('.task-state').text(task_dict.task_state);
var duration_value = (task_dict.task_progress && task_dict.task_progress.duration_ms
- && Math.round(task_dict.task_progress.duration_ms/1000)) || 'unknown';
+ && Math.round(task_dict.task_progress.duration_ms / 1000)) || 'unknown';
entry.find('.task-duration').text(duration_value);
var progress_value = task_dict.message || '';
entry.find('.task-progress').text(progress_value);
@@ -49,7 +47,7 @@
if (task_dict.in_progress === true) {
something_in_progress = true;
} else {
- entry.data('inProgress', "False")
+ entry.data('inProgress', 'False');
}
}
@@ -62,7 +60,7 @@
} else {
delete window.queuePollerID;
}
- }
+ };
InstructorTaskProgress.prototype.get_status = function() {
var _this = this;
@@ -73,7 +71,7 @@
this.entries.each(function(idx, element) {
var task_id = $(element).data('taskId');
var in_progress = $(element).data('inProgress');
- if (in_progress="True") {
+ if (in_progress = 'True') {
task_ids.push(task_id);
}
});
@@ -83,13 +81,12 @@
// in the POST parameter that shows up on the Django server.
// TODO: add error handler.
var ajax_url = '/instructor_task_status/';
- var data = {'task_ids': task_ids };
+ var data = {'task_ids': task_ids};
$.post(ajax_url, data).done(this.update_progress);
};
return InstructorTaskProgress;
})();
-
}).call(this);
// once the page is rendered, create the progress object
diff --git a/lms/static/js/search/base/collections/search_collection.js b/lms/static/js/search/base/collections/search_collection.js
index 2d32cabd27..3e62446f34 100644
--- a/lms/static/js/search/base/collections/search_collection.js
+++ b/lms/static/js/search/base/collections/search_collection.js
@@ -1,108 +1,104 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'backbone',
+ 'js/search/base/models/search_result'
+ ], function(Backbone, SearchResult) {
+ 'use strict';
-define([
- 'backbone',
- 'js/search/base/models/search_result'
-], function (Backbone, SearchResult) {
- 'use strict';
+ return Backbone.Collection.extend({
- return Backbone.Collection.extend({
+ model: SearchResult,
+ pageSize: 20,
+ totalCount: 0,
+ latestModelsCount: 0,
+ accessDeniedCount: 0,
+ searchTerm: '',
+ page: 0,
+ url: '/search/',
+ fetchXhr: null,
- model: SearchResult,
- pageSize: 20,
- totalCount: 0,
- latestModelsCount: 0,
- accessDeniedCount: 0,
- searchTerm: '',
- page: 0,
- url: '/search/',
- fetchXhr: null,
-
- initialize: function (models, options) {
+ initialize: function(models, options) {
// call super constructor
- Backbone.Collection.prototype.initialize.apply(this, arguments);
- if (options && options.courseId) {
- this.url += options.courseId;
- }
- },
-
- performSearch: function (searchTerm) {
- this.fetchXhr && this.fetchXhr.abort();
- this.searchTerm = searchTerm || '';
- this.resetState();
- this.fetchXhr = this.fetch({
- data: {
- search_string: searchTerm,
- page_size: this.pageSize,
- page_index: 0
- },
- type: 'POST',
- success: function (self, xhr) {
- self.trigger('search');
- },
- error: function (self, xhr) {
- self.trigger('error');
+ Backbone.Collection.prototype.initialize.apply(this, arguments);
+ if (options && options.courseId) {
+ this.url += options.courseId;
}
- });
- },
+ },
- loadNextPage: function () {
- this.fetchXhr && this.fetchXhr.abort();
- this.fetchXhr = this.fetch({
- data: {
- search_string: this.searchTerm,
- page_size: this.pageSize,
- page_index: this.page + 1
- },
- type: 'POST',
- success: function (self, xhr) {
- self.page += 1;
- self.trigger('next');
- },
- error: function (self, xhr) {
- self.trigger('error');
- },
- add: true,
- reset: false,
- remove: false
- });
- },
+ performSearch: function(searchTerm) {
+ this.fetchXhr && this.fetchXhr.abort();
+ this.searchTerm = searchTerm || '';
+ this.resetState();
+ this.fetchXhr = this.fetch({
+ data: {
+ search_string: searchTerm,
+ page_size: this.pageSize,
+ page_index: 0
+ },
+ type: 'POST',
+ success: function(self, xhr) {
+ self.trigger('search');
+ },
+ error: function(self, xhr) {
+ self.trigger('error');
+ }
+ });
+ },
- cancelSearch: function () {
- this.fetchXhr && this.fetchXhr.abort();
- this.resetState();
- },
+ loadNextPage: function() {
+ this.fetchXhr && this.fetchXhr.abort();
+ this.fetchXhr = this.fetch({
+ data: {
+ search_string: this.searchTerm,
+ page_size: this.pageSize,
+ page_index: this.page + 1
+ },
+ type: 'POST',
+ success: function(self, xhr) {
+ self.page += 1;
+ self.trigger('next');
+ },
+ error: function(self, xhr) {
+ self.trigger('error');
+ },
+ add: true,
+ reset: false,
+ remove: false
+ });
+ },
- parse: function(response) {
- this.latestModelsCount = response.results.length;
- this.totalCount = response.total;
- this.accessDeniedCount += response.access_denied_count;
- this.totalCount -= this.accessDeniedCount;
- return _.map(response.results, function (result) {
- return result.data;
- });
- },
+ cancelSearch: function() {
+ this.fetchXhr && this.fetchXhr.abort();
+ this.resetState();
+ },
- resetState: function () {
- this.page = 0;
- this.totalCount = 0;
- this.latestModelsCount = 0;
- this.accessDeniedCount = 0;
+ parse: function(response) {
+ this.latestModelsCount = response.results.length;
+ this.totalCount = response.total;
+ this.accessDeniedCount += response.access_denied_count;
+ this.totalCount -= this.accessDeniedCount;
+ return _.map(response.results, function(result) {
+ return result.data;
+ });
+ },
+
+ resetState: function() {
+ this.page = 0;
+ this.totalCount = 0;
+ this.latestModelsCount = 0;
+ this.accessDeniedCount = 0;
// empty the entire collection
- this.reset();
- },
+ this.reset();
+ },
- hasNextPage: function () {
- return this.totalCount - ((this.page + 1) * this.pageSize) > 0;
- },
+ hasNextPage: function() {
+ return this.totalCount - ((this.page + 1) * this.pageSize) > 0;
+ },
- latestModels: function () {
- return this.last(this.latestModelsCount);
- }
+ latestModels: function() {
+ return this.last(this.latestModelsCount);
+ }
+ });
});
-
-});
-
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/base/models/search_result.js b/lms/static/js/search/base/models/search_result.js
index 63821f7159..eba6503793 100644
--- a/lms/static/js/search/base/models/search_result.js
+++ b/lms/static/js/search/base/models/search_result.js
@@ -1,17 +1,14 @@
-;(function (define) {
+(function(define) {
+ define(['backbone'], function(Backbone) {
+ 'use strict';
-define(['backbone'], function (Backbone) {
- 'use strict';
-
- return Backbone.Model.extend({
- defaults: {
- location: [],
- content_type: '',
- excerpt: '',
- url: ''
- }
+ return Backbone.Model.extend({
+ defaults: {
+ location: [],
+ content_type: '',
+ excerpt: '',
+ url: ''
+ }
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/base/routers/search_router.js b/lms/static/js/search/base/routers/search_router.js
index fc4a7adf21..e85bf7dea3 100644
--- a/lms/static/js/search/base/routers/search_router.js
+++ b/lms/static/js/search/base/routers/search_router.js
@@ -1,17 +1,14 @@
-;(function (define) {
+(function(define) {
+ define(['backbone'], function(Backbone) {
+ 'use strict';
-define(['backbone'], function (Backbone) {
- 'use strict';
-
- return Backbone.Router.extend({
- routes: {
- 'search/:query': 'search'
- },
- search: function(query) {
- this.trigger('search', query);
- }
+ return Backbone.Router.extend({
+ routes: {
+ 'search/:query': 'search'
+ },
+ search: function(query) {
+ this.trigger('search', query);
+ }
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/base/views/search_form.js b/lms/static/js/search/base/views/search_form.js
index 5b666cf6af..c9d6153883 100644
--- a/lms/static/js/search/base/views/search_form.js
+++ b/lms/static/js/search/base/views/search_form.js
@@ -1,69 +1,66 @@
-;(function (define) {
+(function(define) {
+ define(['jquery', 'backbone'], function($, Backbone) {
+ 'use strict';
-define(['jquery', 'backbone'], function ($, Backbone) {
- 'use strict';
+ return Backbone.View.extend({
- return Backbone.View.extend({
+ el: '',
+ events: {
+ 'submit form': 'submitForm',
+ 'click .cancel-button': 'clearSearch'
+ },
- el: '',
- events: {
- 'submit form': 'submitForm',
- 'click .cancel-button': 'clearSearch',
- },
+ initialize: function() {
+ this.$searchField = this.$el.find('.search-field');
+ this.$searchButton = this.$el.find('.search-button');
+ this.$cancelButton = this.$el.find('.cancel-button');
+ },
- initialize: function () {
- this.$searchField = this.$el.find('.search-field');
- this.$searchButton = this.$el.find('.search-button');
- this.$cancelButton = this.$el.find('.cancel-button');
- },
+ submitForm: function(event) {
+ event.preventDefault();
+ this.doSearch();
+ },
- submitForm: function (event) {
- event.preventDefault();
- this.doSearch();
- },
+ doSearch: function(term) {
+ if (term) {
+ this.$searchField.val(term);
+ }
+ else {
+ term = this.$searchField.val();
+ }
- doSearch: function (term) {
- if (term) {
- this.$searchField.val(term);
- }
- else {
- term = this.$searchField.val();
+ var trimmed = $.trim(term);
+ if (trimmed) {
+ this.setActiveStyle();
+ this.trigger('search', trimmed);
+ }
+ else {
+ this.clearSearch();
+ }
+ },
+
+ resetSearchForm: function() {
+ this.$searchField.val('');
+ this.setInitialStyle();
+ },
+
+ clearSearch: function() {
+ this.resetSearchForm();
+ this.trigger('clear');
+ },
+
+ setActiveStyle: function() {
+ this.$searchField.addClass('is-active');
+ this.$searchButton.hide();
+ this.$cancelButton.show();
+ },
+
+ setInitialStyle: function() {
+ this.$searchField.removeClass('is-active');
+ this.$searchButton.show();
+ this.$cancelButton.hide();
}
- var trimmed = $.trim(term);
- if (trimmed) {
- this.setActiveStyle();
- this.trigger('search', trimmed);
- }
- else {
- this.clearSearch();
- }
- },
-
- resetSearchForm: function () {
- this.$searchField.val('');
- this.setInitialStyle();
- },
-
- clearSearch: function () {
- this.resetSearchForm();
- this.trigger('clear');
- },
-
- setActiveStyle: function () {
- this.$searchField.addClass('is-active');
- this.$searchButton.hide();
- this.$cancelButton.show();
- },
-
- setInitialStyle: function () {
- this.$searchField.removeClass('is-active');
- this.$searchButton.show();
- this.$cancelButton.hide();
- }
-
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/base/views/search_item_view.js b/lms/static/js/search/base/views/search_item_view.js
index 57ddaeb226..8d406a0368 100644
--- a/lms/static/js/search/base/views/search_item_view.js
+++ b/lms/static/js/search/base/views/search_item_view.js
@@ -1,73 +1,70 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'gettext',
+ 'logger'
+ ], function($, _, Backbone, gettext, Logger) {
+ 'use strict';
-define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'gettext',
- 'logger'
-], function ($, _, Backbone, gettext, Logger) {
- 'use strict';
+ return Backbone.View.extend({
- return Backbone.View.extend({
+ tagName: 'li',
+ templateId: '',
+ className: 'search-results-item',
+ attributes: {
+ 'role': 'region',
+ 'aria-label': 'search result'
+ },
- tagName: 'li',
- templateId: '',
- className: 'search-results-item',
- attributes: {
- 'role': 'region',
- 'aria-label': 'search result'
- },
+ events: {
+ 'click': 'logSearchItem'
+ },
- events: {
- 'click': 'logSearchItem',
- },
+ initialize: function() {
+ this.tpl = _.template($(this.templateId).html());
+ },
- initialize: function () {
- this.tpl = _.template($(this.templateId).html());
- },
-
- render: function () {
- var data = _.clone(this.model.attributes);
+ render: function() {
+ var data = _.clone(this.model.attributes);
// Drop the preview text and result type if the search term is found
// in the title/location in the course hierarchy
- if (this.model.get('content_type') === 'Sequence') {
- data.excerpt = '';
- data.content_type = '';
- }
- this.$el.html(this.tpl(data));
- return this;
- },
+ if (this.model.get('content_type') === 'Sequence') {
+ data.excerpt = '';
+ data.content_type = '';
+ }
+ this.$el.html(this.tpl(data));
+ return this;
+ },
/**
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function(url) {
- window.location.href = url;
- },
+ redirect: function(url) {
+ window.location.href = url;
+ },
- logSearchItem: function(event) {
- event.preventDefault();
- var self = this;
- var target = this.model.id;
- var link = this.model.get('url');
- var collection = this.model.collection;
- var page = collection.page;
- var pageSize = collection.pageSize;
- var searchTerm = collection.searchTerm;
- var index = collection.indexOf(this.model);
- Logger.log('edx.course.search.result_selected', {
- 'search_term': searchTerm,
- 'result_position': (page * pageSize + index),
- 'result_link': target
- }).always(function() {
- self.redirect(link);
- });
- }
+ logSearchItem: function(event) {
+ event.preventDefault();
+ var self = this;
+ var target = this.model.id;
+ var link = this.model.get('url');
+ var collection = this.model.collection;
+ var page = collection.page;
+ var pageSize = collection.pageSize;
+ var searchTerm = collection.searchTerm;
+ var index = collection.indexOf(this.model);
+ Logger.log('edx.course.search.result_selected', {
+ 'search_term': searchTerm,
+ 'result_position': (page * pageSize + index),
+ 'result_link': target
+ }).always(function() {
+ self.redirect(link);
+ });
+ }
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/base/views/search_results_view.js b/lms/static/js/search/base/views/search_results_view.js
index 50ec668767..55e31219ad 100644
--- a/lms/static/js/search/base/views/search_results_view.js
+++ b/lms/static/js/search/base/views/search_results_view.js
@@ -1,110 +1,105 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'gettext'
+ ], function($, _, Backbone, gettext) {
+ 'use strict';
-define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'gettext',
-], function ($, _, Backbone, gettext) {
-
- 'use strict';
-
- return Backbone.View.extend({
+ return Backbone.View.extend({
// these should be defined by subclasses
- el: '',
- contentElement: '',
- resultsTemplateId: '',
- loadingTemplateId: '',
- errorTemplateId: '',
- events: {},
- spinner: '.search-load-next .icon',
- SearchItemView: function () {},
+ el: '',
+ contentElement: '',
+ resultsTemplateId: '',
+ loadingTemplateId: '',
+ errorTemplateId: '',
+ events: {},
+ spinner: '.search-load-next .icon',
+ SearchItemView: function() {},
- initialize: function () {
- this.$contentElement = $(this.contentElement);
- this.resultsTemplate = _.template($(this.resultsTemplateId).html());
- this.loadingTemplate = _.template($(this.loadingTemplateId).html());
- this.errorTemplate = _.template($(this.errorTemplateId).html());
- },
+ initialize: function() {
+ this.$contentElement = $(this.contentElement);
+ this.resultsTemplate = _.template($(this.resultsTemplateId).html());
+ this.loadingTemplate = _.template($(this.loadingTemplateId).html());
+ this.errorTemplate = _.template($(this.errorTemplateId).html());
+ },
- render: function () {
- this.$el.html(this.resultsTemplate({
- totalCount: this.collection.totalCount,
- totalCountMsg: this.totalCountMsg(),
- pageSize: this.collection.pageSize,
- hasMoreResults: this.collection.hasNextPage()
- }));
- this.renderItems();
- this.$el.find(this.spinner).hide();
- this.showResults();
- return this;
- },
+ render: function() {
+ this.$el.html(this.resultsTemplate({
+ totalCount: this.collection.totalCount,
+ totalCountMsg: this.totalCountMsg(),
+ pageSize: this.collection.pageSize,
+ hasMoreResults: this.collection.hasNextPage()
+ }));
+ this.renderItems();
+ this.$el.find(this.spinner).hide();
+ this.showResults();
+ return this;
+ },
- renderNext: function () {
+ renderNext: function() {
// total count may have changed
- this.$el.find('.search-count').text(this.totalCountMsg());
- this.renderItems();
- if (! this.collection.hasNextPage()) {
- this.$el.find('.search-load-next').remove();
- }
- this.$el.find(this.spinner).hide();
- },
+ this.$el.find('.search-count').text(this.totalCountMsg());
+ this.renderItems();
+ if (! this.collection.hasNextPage()) {
+ this.$el.find('.search-load-next').remove();
+ }
+ this.$el.find(this.spinner).hide();
+ },
- renderItems: function () {
- var latest = this.collection.latestModels();
- var items = latest.map(function (result) {
- var item = new this.SearchItemView({ model: result });
- return item.render().el;
- }, this);
- this.$el.find('ol').append(items);
- },
+ renderItems: function() {
+ var latest = this.collection.latestModels();
+ var items = latest.map(function(result) {
+ var item = new this.SearchItemView({model: result});
+ return item.render().el;
+ }, this);
+ this.$el.find('ol').append(items);
+ },
- totalCountMsg: function () {
- var fmt = ngettext('%s result', '%s results', this.collection.totalCount);
- return interpolate(fmt, [this.collection.totalCount]);
- },
+ totalCountMsg: function() {
+ var fmt = ngettext('%s result', '%s results', this.collection.totalCount);
+ return interpolate(fmt, [this.collection.totalCount]);
+ },
- clear: function () {
- this.$el.hide().empty();
- this.$contentElement.show();
- },
+ clear: function() {
+ this.$el.hide().empty();
+ this.$contentElement.show();
+ },
- showResults: function() {
- this.$el.show();
- this.$contentElement.hide();
- },
+ showResults: function() {
+ this.$el.show();
+ this.$contentElement.hide();
+ },
- showLoadingMessage: function () {
- this.doCleanup();
- this.$el.html(this.loadingTemplate());
- this.showResults();
- },
+ showLoadingMessage: function() {
+ this.doCleanup();
+ this.$el.html(this.loadingTemplate());
+ this.showResults();
+ },
- showErrorMessage: function () {
- this.$el.html(this.errorTemplate());
- this.showResults();
- },
+ showErrorMessage: function() {
+ this.$el.html(this.errorTemplate());
+ this.showResults();
+ },
- doCleanup: function () {
+ doCleanup: function() {
// Empty any loading/error message and empty the el
// Bookmarks share the same container element, So we are doing
// this to ensure that elements are in clean/initial state
- $('#loading-message').html('');
- $('#error-message').html('');
- this.$el.html('');
- },
+ $('#loading-message').html('');
+ $('#error-message').html('');
+ this.$el.html('');
+ },
- loadNext: function (event) {
- event && event.preventDefault();
- this.$el.find(this.spinner).show();
- this.trigger('next');
- return false;
- }
+ loadNext: function(event) {
+ event && event.preventDefault();
+ this.$el.find(this.spinner).show();
+ this.trigger('next');
+ return false;
+ }
+ });
});
-
-});
-
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/course/course_search_factory.js b/lms/static/js/search/course/course_search_factory.js
index 4f2a68d916..dce1a1acf2 100644
--- a/lms/static/js/search/course/course_search_factory.js
+++ b/lms/static/js/search/course/course_search_factory.js
@@ -1,52 +1,47 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone', 'js/search/base/routers/search_router', 'js/search/course/views/search_form',
'js/search/base/collections/search_collection', 'js/search/course/views/search_results_view'],
function(Backbone, SearchRouter, CourseSearchForm, SearchCollection, SearchResultsView) {
-
- return function (courseId) {
-
+ return function(courseId) {
var router = new SearchRouter();
var form = new CourseSearchForm();
- var collection = new SearchCollection([], { courseId: courseId });
- var results = new SearchResultsView({ collection: collection });
+ var collection = new SearchCollection([], {courseId: courseId});
+ var results = new SearchResultsView({collection: collection});
var dispatcher = _.clone(Backbone.Events);
- dispatcher.listenTo(router, 'search', function (query) {
+ dispatcher.listenTo(router, 'search', function(query) {
form.doSearch(query);
});
- dispatcher.listenTo(form, 'search', function (query) {
+ dispatcher.listenTo(form, 'search', function(query) {
results.showLoadingMessage();
collection.performSearch(query);
- router.navigate('search/' + query, { replace: true });
+ router.navigate('search/' + query, {replace: true});
});
- dispatcher.listenTo(form, 'clear', function () {
+ dispatcher.listenTo(form, 'clear', function() {
collection.cancelSearch();
results.clear();
router.navigate('');
});
- dispatcher.listenTo(results, 'next', function () {
+ dispatcher.listenTo(results, 'next', function() {
collection.loadNextPage();
});
- dispatcher.listenTo(collection, 'search', function () {
+ dispatcher.listenTo(collection, 'search', function() {
results.render();
});
- dispatcher.listenTo(collection, 'next', function () {
+ dispatcher.listenTo(collection, 'next', function() {
results.renderNext();
});
- dispatcher.listenTo(collection, 'error', function () {
+ dispatcher.listenTo(collection, 'error', function() {
results.showErrorMessage();
});
-
};
-
});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/course/views/search_form.js b/lms/static/js/search/course/views/search_form.js
index 8bee186a24..3d2e175d21 100644
--- a/lms/static/js/search/course/views/search_form.js
+++ b/lms/static/js/search/course/views/search_form.js
@@ -1,14 +1,11 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'js/search/base/views/search_form'
+ ], function(SearchForm) {
+ 'use strict';
-define([
- 'js/search/base/views/search_form'
-], function (SearchForm) {
- 'use strict';
-
- return SearchForm.extend({
- el: '#courseware-search-bar'
+ return SearchForm.extend({
+ el: '#courseware-search-bar'
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/course/views/search_item_view.js b/lms/static/js/search/course/views/search_item_view.js
index cd130b2240..57181fcee6 100644
--- a/lms/static/js/search/course/views/search_item_view.js
+++ b/lms/static/js/search/course/views/search_item_view.js
@@ -1,14 +1,11 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'js/search/base/views/search_item_view'
+ ], function(SearchItemView) {
+ 'use strict';
-define([
- 'js/search/base/views/search_item_view'
-], function (SearchItemView) {
- 'use strict';
-
- return SearchItemView.extend({
- templateId: '#course_search_item-tpl'
+ return SearchItemView.extend({
+ templateId: '#course_search_item-tpl'
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/course/views/search_results_view.js b/lms/static/js/search/course/views/search_results_view.js
index b1bfc3edaa..0d592c7163 100644
--- a/lms/static/js/search/course/views/search_results_view.js
+++ b/lms/static/js/search/course/views/search_results_view.js
@@ -1,38 +1,34 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'js/search/base/views/search_results_view',
+ 'js/search/course/views/search_item_view'
+ ], function(SearchResultsView, CourseSearchItemView) {
+ 'use strict';
-define([
- 'js/search/base/views/search_results_view',
- 'js/search/course/views/search_item_view'
-], function (SearchResultsView, CourseSearchItemView) {
- 'use strict';
+ return SearchResultsView.extend({
- return SearchResultsView.extend({
+ el: '.courseware-results',
+ contentElement: '#course-content',
+ coursewareResultsWrapperElement: '.courseware-results-wrapper',
+ resultsTemplateId: '#course_search_results-tpl',
+ loadingTemplateId: '#search_loading-tpl',
+ errorTemplateId: '#search_error-tpl',
+ events: {
+ 'click .search-load-next': 'loadNext'
+ },
+ SearchItemView: CourseSearchItemView,
- el: '.courseware-results',
- contentElement: '#course-content',
- coursewareResultsWrapperElement: '.courseware-results-wrapper',
- resultsTemplateId: '#course_search_results-tpl',
- loadingTemplateId: '#search_loading-tpl',
- errorTemplateId: '#search_error-tpl',
- events: {
- 'click .search-load-next': 'loadNext',
- },
- SearchItemView: CourseSearchItemView,
+ clear: function() {
+ SearchResultsView.prototype.clear.call(this);
+ $(this.coursewareResultsWrapperElement).hide();
+ this.$contentElement.css('display', 'table-cell');
+ },
- clear: function () {
- SearchResultsView.prototype.clear.call(this);
- $(this.coursewareResultsWrapperElement).hide();
- this.$contentElement.css('display', 'table-cell');
- },
-
- showResults: function () {
- SearchResultsView.prototype.showResults.call(this);
- $(this.coursewareResultsWrapperElement).css('display', 'table-cell');
- }
+ showResults: function() {
+ SearchResultsView.prototype.showResults.call(this);
+ $(this.coursewareResultsWrapperElement).css('display', 'table-cell');
+ }
+ });
});
-
-});
-
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/dashboard/dashboard_search_factory.js b/lms/static/js/search/dashboard/dashboard_search_factory.js
index f44215c416..29b96d0ee4 100644
--- a/lms/static/js/search/dashboard/dashboard_search_factory.js
+++ b/lms/static/js/search/dashboard/dashboard_search_factory.js
@@ -1,56 +1,51 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone', 'js/search/base/routers/search_router', 'js/search/dashboard/views/search_form',
'js/search/base/collections/search_collection', 'js/search/dashboard/views/search_results_view'],
function(Backbone, SearchRouter, SearchForm, SearchCollection, SearchListView) {
-
- return function () {
-
+ return function() {
var router = new SearchRouter();
var form = new SearchForm();
var collection = new SearchCollection([]);
- var results = new SearchListView({ collection: collection });
+ var results = new SearchListView({collection: collection});
var dispatcher = _.clone(Backbone.Events);
- dispatcher.listenTo(router, 'search', function (query) {
+ dispatcher.listenTo(router, 'search', function(query) {
form.doSearch(query);
});
- dispatcher.listenTo(form, 'search', function (query) {
+ dispatcher.listenTo(form, 'search', function(query) {
results.showLoadingMessage();
collection.performSearch(query);
- router.navigate('search/' + query, { replace: true });
+ router.navigate('search/' + query, {replace: true});
});
- dispatcher.listenTo(form, 'clear', function () {
+ dispatcher.listenTo(form, 'clear', function() {
collection.cancelSearch();
results.clear();
router.navigate('');
});
- dispatcher.listenTo(results, 'next', function () {
+ dispatcher.listenTo(results, 'next', function() {
collection.loadNextPage();
});
- dispatcher.listenTo(results, 'reset', function () {
+ dispatcher.listenTo(results, 'reset', function() {
form.resetSearchForm();
});
- dispatcher.listenTo(collection, 'search', function () {
+ dispatcher.listenTo(collection, 'search', function() {
results.render();
});
- dispatcher.listenTo(collection, 'next', function () {
+ dispatcher.listenTo(collection, 'next', function() {
results.renderNext();
});
- dispatcher.listenTo(collection, 'error', function () {
+ dispatcher.listenTo(collection, 'error', function() {
results.showErrorMessage();
});
-
};
-
});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/dashboard/views/search_form.js b/lms/static/js/search/dashboard/views/search_form.js
index 8c3a4e62e4..b302235af5 100644
--- a/lms/static/js/search/dashboard/views/search_form.js
+++ b/lms/static/js/search/dashboard/views/search_form.js
@@ -1,14 +1,11 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'js/search/base/views/search_form'
+ ], function(SearchForm) {
+ 'use strict';
-define([
- 'js/search/base/views/search_form'
-], function (SearchForm) {
- 'use strict';
-
- return SearchForm.extend({
- el: '#dashboard-search-bar'
+ return SearchForm.extend({
+ el: '#dashboard-search-bar'
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/dashboard/views/search_item_view.js b/lms/static/js/search/dashboard/views/search_item_view.js
index d577e2f1f0..9663533377 100644
--- a/lms/static/js/search/dashboard/views/search_item_view.js
+++ b/lms/static/js/search/dashboard/views/search_item_view.js
@@ -1,14 +1,11 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'js/search/base/views/search_item_view'
+ ], function(SearchItemView) {
+ 'use strict';
-define([
- 'js/search/base/views/search_item_view'
-], function (SearchItemView) {
- 'use strict';
-
- return SearchItemView.extend({
- templateId: '#dashboard_search_item-tpl'
+ return SearchItemView.extend({
+ templateId: '#dashboard_search_item-tpl'
+ });
});
-
-});
-
})(define || RequireJS.define);
diff --git a/lms/static/js/search/dashboard/views/search_results_view.js b/lms/static/js/search/dashboard/views/search_results_view.js
index b94826e0cf..5b8f50a65a 100644
--- a/lms/static/js/search/dashboard/views/search_results_view.js
+++ b/lms/static/js/search/dashboard/views/search_results_view.js
@@ -1,33 +1,29 @@
-;(function (define) {
+(function(define) {
+ define([
+ 'js/search/base/views/search_results_view',
+ 'js/search/dashboard/views/search_item_view'
+ ], function(SearchResultsView, DashSearchItemView) {
+ 'use strict';
-define([
- 'js/search/base/views/search_results_view',
- 'js/search/dashboard/views/search_item_view'
-], function (SearchResultsView, DashSearchItemView) {
- 'use strict';
+ return SearchResultsView.extend({
- return SearchResultsView.extend({
+ el: '#dashboard-search-results',
+ contentElement: '#my-courses, #profile-sidebar',
+ resultsTemplateId: '#dashboard_search_results-tpl',
+ loadingTemplateId: '#search_loading-tpl',
+ errorTemplateId: '#search_error-tpl',
+ events: {
+ 'click .search-load-next': 'loadNext',
+ 'click .search-back-to-courses': 'backToCourses'
+ },
+ SearchItemView: DashSearchItemView,
- el: '#dashboard-search-results',
- contentElement: '#my-courses, #profile-sidebar',
- resultsTemplateId: '#dashboard_search_results-tpl',
- loadingTemplateId: '#search_loading-tpl',
- errorTemplateId: '#search_error-tpl',
- events: {
- 'click .search-load-next': 'loadNext',
- 'click .search-back-to-courses': 'backToCourses'
- },
- SearchItemView: DashSearchItemView,
-
- backToCourses: function () {
- this.clear();
- this.trigger('reset');
- return false;
- }
+ backToCourses: function() {
+ this.clear();
+ this.trigger('reset');
+ return false;
+ }
+ });
});
-
-});
-
-
})(define || RequireJS.define);
diff --git a/lms/static/js/shoppingcart/shoppingcart.js b/lms/static/js/shoppingcart/shoppingcart.js
index 971bc8c512..4301de74eb 100644
--- a/lms/static/js/shoppingcart/shoppingcart.js
+++ b/lms/static/js/shoppingcart/shoppingcart.js
@@ -28,8 +28,8 @@ var edx = edx || {};
*/
var isCourseEnrollmentAllowed = function() {
return $.ajax({
- url: "/shoppingcart/verify_cart/",
- type: "GET"
+ url: '/shoppingcart/verify_cart/',
+ type: 'GET'
});
};
@@ -66,7 +66,7 @@ var edx = edx || {};
}
// Immediately disable the submit button to prevent duplicate submissions
- this.$el.find('input[type="submit"]').addClass("disabled");
+ this.$el.find('input[type="submit"]').addClass('disabled');
this.$paymentForm = this.$el;
isCourseEnrollmentAllowed()
@@ -84,7 +84,7 @@ var edx = edx || {};
*/
responseFromServer: function(data) {
if (data.is_course_enrollment_closed == true) {
- location.href = "/shoppingcart";
+ location.href = '/shoppingcart';
}
else {
this.submitPaymentForm(this.$paymentForm);
@@ -97,13 +97,13 @@ var edx = edx || {};
*/
errorFromServer: function() {
// Immediately enable the submit button to allow submission
- this.$el.find('input[type="submit"]').removeClass("disabled");
+ this.$el.find('input[type="submit"]').removeClass('disabled');
},
/**
* Submit the payment from to the external payment processor.
*
- * @param {Object} form
+ * @param {Object} form
*/
submitPaymentForm: function(form) {
form.submit();
@@ -121,14 +121,14 @@ var edx = edx || {};
// before going to make payment
// if exists then trigger click event of the apply code button
var code = $('div.code-input input#input_code').val();
- if (typeof(code) != 'undefined' && code != ''){
- $('div.code-input #submit-code').trigger('click');
+ if (typeof(code) != 'undefined' && code != '') {
+ $('div.code-input #submit-code').trigger('click');
return false;
}
var container = $('.confirm-enrollment.cart-view form');
var view = new edx.shoppingcart.showcart.CartView({
- el:container
+ el: container
}).submit(event);
});
});
-})(jQuery);
\ No newline at end of file
+})(jQuery);
diff --git a/lms/static/js/spec/api_admin/catalog_preview_spec.js b/lms/static/js/spec/api_admin/catalog_preview_spec.js
index b14c02591f..6a1545cbfa 100644
--- a/lms/static/js/spec/api_admin/catalog_preview_spec.js
+++ b/lms/static/js/spec/api_admin/catalog_preview_spec.js
@@ -1,17 +1,17 @@
define([
'js/api_admin/views/catalog_preview',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
-], function (
+], function(
CatalogPreviewView, AjaxHelpers
) {
'use strict';
- describe('Catalog preview view', function () {
+ describe('Catalog preview view', function() {
var view,
previewUrl = 'http://example.com/api-admin/catalogs/preview/',
catalogApiUrl = 'http://api.example.com/catalog/v1/courses/';
- beforeEach(function () {
+ beforeEach(function() {
setFixtures(
'' +
'
' +
@@ -21,16 +21,16 @@ define([
view = new CatalogPreviewView({
el: '.catalog-body',
previewUrl: previewUrl,
- catalogApiUrl: catalogApiUrl,
+ catalogApiUrl: catalogApiUrl
});
view.render();
});
- it('can render itself', function () {
+ it('can render itself', function() {
expect(view.$('button.preview-query').length).toBe(1);
});
- it('can retrieve a list of catalogs and display them', function () {
+ it('can retrieve a list of catalogs and display them', function() {
var requests = AjaxHelpers.requests(this);
view.$('#id_query').val('*');
view.$('.preview-query').click();
@@ -39,13 +39,13 @@ define([
results: [{key: 'TestX', title: 'Test Course'}],
count: 1,
next: null,
- prev: null,
+ prev: null
});
expect(view.$('.preview-results').text()).toContain('Test Course');
expect(view.$('.preview-results-list li a').attr('href')).toEqual(catalogApiUrl + 'TestX');
});
- it('displays an error when courses cannot be retrieved', function () {
+ it('displays an error when courses cannot be retrieved', function() {
var requests = AjaxHelpers.requests(this);
view.$('#id_query').val('*');
view.$('.preview-query').click();
diff --git a/lms/static/js/spec/ccx/schedule_spec.js b/lms/static/js/spec/ccx/schedule_spec.js
index cb55bebce0..4757ae5ae5 100644
--- a/lms/static/js/spec/ccx/schedule_spec.js
+++ b/lms/static/js/spec/ccx/schedule_spec.js
@@ -1,15 +1,15 @@
define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
function(AjaxHelpers) {
- describe("edx.ccx.schedule.ScheduleView", function() {
+ describe('edx.ccx.schedule.ScheduleView', function() {
var view = null;
var data;
beforeEach(function() {
- loadFixtures("js/fixtures/ccx/schedule.html");
+ loadFixtures('js/fixtures/ccx/schedule.html');
- var scheduleFixture = readFixtures("templates/ccx/schedule.underscore");
+ var scheduleFixture = readFixtures('templates/ccx/schedule.underscore');
appendSetFixtures(
- ""
+ ''
);
schedule_template = _.template($('#schedule_template').html());
save_url = 'save_ccx';
@@ -19,30 +19,30 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
};
data = [{
- "category": "chapter",
- "display_name": "Introduction",
- "due": null,
- "start": null,
- "location": "i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b",
- "hidden": true,
- "children": [
+ 'category': 'chapter',
+ 'display_name': 'Introduction',
+ 'due': null,
+ 'start': null,
+ 'location': 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b',
+ 'hidden': true,
+ 'children': [
{
- "category": "sequential",
- "display_name": "Demo Course Overview",
- "due": null,
- "start": null,
- "location": "i4x://edX/DemoX/sequential/edx_introduction",
- "hidden": true,
- "children": [
- {
- "category": "vertical",
- "display_name": "Introduction: Video and Sequences",
- "due": null,
- "start": null,
- "location": "i4x://edX/DemoX/vertical/vertical_0270f6de40fc",
- "hidden": true
- }
- ]
+ 'category': 'sequential',
+ 'display_name': 'Demo Course Overview',
+ 'due': null,
+ 'start': null,
+ 'location': 'i4x://edX/DemoX/sequential/edx_introduction',
+ 'hidden': true,
+ 'children': [
+ {
+ 'category': 'vertical',
+ 'display_name': 'Introduction: Video and Sequences',
+ 'due': null,
+ 'start': null,
+ 'location': 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc',
+ 'hidden': true
+ }
+ ]
}
]
}];
@@ -51,39 +51,39 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
view.render();
});
- it("verifies correct view setup", function() {
+ it('verifies correct view setup', function() {
expect(view.dirty).toBe(false);
expect(view.showing).toEqual([]);
expect(view.hidden).toEqual(data);
expect(view.schedule).toEqual(data);
});
- it("finds a unit", function() {
+ it('finds a unit', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
expect(unit).toEqual(data[0]);
});
- it("hides a unit", function() {
+ it('hides a unit', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
unit.hidden = false;
view.hide(unit);
expect(unit.hidden).toBe(true);
});
- it("shows a unit", function() {
+ it('shows a unit', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
view.show(unit);
expect(unit.hidden).toBe(false);
});
- it("applies function to schedule nodes", function() {
+ it('applies function to schedule nodes', function() {
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
expect(unit.hidden).toBe(true);
- view.schedule_apply(view.schedule, view.show)
+ view.schedule_apply(view.schedule, view.show);
expect(unit.hidden).toBe(false);
});
- it("adds all units to schedule", function() {
+ it('adds all units to schedule', function() {
expect(view.showing).toEqual([]);
expect(view.hidden.length).toEqual(1);
$('#add-all').click();
@@ -91,7 +91,7 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(view.hidden).toEqual([]);
});
- it("selects a chapter and adds units to dropdown", function() {
+ it('selects a chapter and adds units to dropdown', function() {
expect(view.sequential_select.children('option').length).toEqual(0);
view.chapter_select.change();
expect(view.sequential_select.prop('disabled')).toEqual(true);
@@ -103,14 +103,14 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(view.sequential_select.children('option').length).toEqual(2);
});
- it("selects a unit and adds sections to dropdown", function() {
+ it('selects a unit and adds sections to dropdown', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
expect(view.vertical_select.children('option').length).toEqual(0);
view.sequential_select.change();
expect(view.vertical_select.prop('disabled')).toEqual(true);
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
expect(view.sequential_select.val()).toEqual(val);
@@ -118,27 +118,27 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(view.vertical_select.children('option').length).toEqual(2);
});
- it("selects a section", function() {
+ it('selects a section', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc";
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc';
view.vertical_select.val(val);
view.vertical_select.change();
expect(view.vertical_select.val()).toEqual(val);
});
- it("adds a unit", function() {
+ it('adds a unit', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc",
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc',
view.vertical_select.val(val);
view.vertical_select.change();
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
@@ -149,14 +149,14 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(unit.hidden).toBe(false);
});
- it("add unit when start date is greater the due date", function() {
+ it('add unit when start date is greater the due date', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc";
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc';
view.vertical_select.val(val);
view.vertical_select.change();
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
@@ -169,14 +169,14 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(unit.hidden).toBe(true);
});
- it("add unit when start date is missing", function() {
+ it('add unit when start date is missing', function() {
var val = 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b';
view.chapter_select.val(val);
view.chapter_select.change();
- val = "i4x://edX/DemoX/sequential/edx_introduction";
+ val = 'i4x://edX/DemoX/sequential/edx_introduction';
view.sequential_select.val(val);
view.sequential_select.change();
- val = "i4x://edX/DemoX/vertical/vertical_0270f6de40fc";
+ val = 'i4x://edX/DemoX/vertical/vertical_0270f6de40fc';
view.vertical_select.val(val);
view.vertical_select.change();
var unit = view.find_unit(view.schedule, 'i4x://edX/DemoX/chapter/d8a6192ade314473a78242dfeedfbf5b');
@@ -189,39 +189,38 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'],
expect(unit.hidden).toBe(true);
});
- it("gets a datetime string from date and time fields", function() {
+ it('gets a datetime string from date and time fields', function() {
view.set_datetime('start', '2015-12-12 10:45');
expect($('form#add-unit input[name=start_date]')).toHaveValue('2015-12-12');
expect($('form#add-unit input[name=start_time]')).toHaveValue('10:45');
});
- it("sets date and time fields from datetime string", function() {
+ it('sets date and time fields from datetime string', function() {
$('form#add-unit input[name=start_date]').val('2015-12-12');
$('form#add-unit input[name=start_time]').val('10:45');
var datetime = view.get_datetime('start');
expect(datetime).toBe('2015-12-12 10:45');
});
- it("saves schedule changes", function() {
- requests = AjaxHelpers["requests"](this)
+ it('saves schedule changes', function() {
+ requests = AjaxHelpers['requests'](this);
view.save();
- expect(requests.length).toEqual(1)
+ expect(requests.length).toEqual(1);
AjaxHelpers.expectJsonRequest(requests, 'POST', 'save_ccx', view.schedule);
- expect($('#dirty-schedule #save-changes').text()).toEqual("Saving");
+ expect($('#dirty-schedule #save-changes').text()).toEqual('Saving');
AjaxHelpers.respondWithJson(requests, {
data: view.schedule
});
- expect($('#dirty-schedule #save-changes').text()).toEqual("Save changes");
+ expect($('#dirty-schedule #save-changes').text()).toEqual('Save changes');
expect($('#ajax-error')).toHaveCss({display: 'none'});
});
- it("displays an error if the sync fails", function() {
- requests = AjaxHelpers["requests"](this)
+ it('displays an error if the sync fails', function() {
+ requests = AjaxHelpers['requests'](this);
view.save();
requests[0].respond(500);
expect($('#ajax-error')).toHaveCss({display: 'block'});
});
-
});
}
);
diff --git a/lms/static/js/spec/commerce/receipt_view_spec.js b/lms/static/js/spec/commerce/receipt_view_spec.js
index b30570e6f1..ff42f05fc0 100644
--- a/lms/static/js/spec/commerce/receipt_view_spec.js
+++ b/lms/static/js/spec/commerce/receipt_view_spec.js
@@ -1,10 +1,10 @@
define([
- 'jquery',
- 'jquery.ajax-retry',
- 'js/commerce/views/receipt_view',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
- ],
- function ($, AjaxRetry, ReceiptView, AjaxHelpers) {
+ 'jquery',
+ 'jquery.ajax-retry',
+ 'js/commerce/views/receipt_view',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
+],
+ function($, AjaxRetry, ReceiptView, AjaxHelpers) {
'use strict';
describe('edx.commerce.ReceiptView', function() {
var data, courseResponseData, providerResponseData, mockRequests, mockRender, createReceiptView,
@@ -15,17 +15,17 @@ define([
};
mockRequests = function(requests, method, apiUrl, responseData) {
- AjaxHelpers.expectRequest(requests, method, apiUrl);
- AjaxHelpers.respondWithJson(requests, responseData);
+ AjaxHelpers.expectRequest(requests, method, apiUrl);
+ AjaxHelpers.respondWithJson(requests, responseData);
};
mockRender = function(useEcommerceOrderNumber, isVerified) {
var requests, view, orderUrlFormat;
requests = AjaxHelpers.requests(this);
- $("#receipt-container").data("verified", isVerified);
+ $('#receipt-container').data('verified', isVerified);
view = createReceiptView();
view.useEcommerceApi = true;
- if (useEcommerceOrderNumber){
+ if (useEcommerceOrderNumber) {
view.ecommerceOrderNumber = 'EDX-123456';
orderUrlFormat = '/api/commerce/v1/orders/EDX-123456/';
}
@@ -68,92 +68,92 @@ define([
);
data = {
- "status": "Open",
- "billed_to": {
- "city": "dummy city",
- "first_name": "john",
- "last_name": "doe",
- "country": "AL",
- "line2": "line2",
- "line1": "line1",
- "state": "",
- "postcode": "12345"
+ 'status': 'Open',
+ 'billed_to': {
+ 'city': 'dummy city',
+ 'first_name': 'john',
+ 'last_name': 'doe',
+ 'country': 'AL',
+ 'line2': 'line2',
+ 'line1': 'line1',
+ 'state': '',
+ 'postcode': '12345'
},
- "lines": [
+ 'lines': [
{
- "status": "Open",
- "unit_price_excl_tax": "10.00",
- "product": {
- "attribute_values": [
+ 'status': 'Open',
+ 'unit_price_excl_tax': '10.00',
+ 'product': {
+ 'attribute_values': [
{
- "name": "certificate_type",
- "value": "verified"
+ 'name': 'certificate_type',
+ 'value': 'verified'
},
{
- "name": "course_key",
- "code": "course_key",
- "value": "course-v1:edx+dummy+2015_T3"
+ 'name': 'course_key',
+ 'code': 'course_key',
+ 'value': 'course-v1:edx+dummy+2015_T3'
},
{
- "name": "credit_provider",
- "value": "edx"
+ 'name': 'credit_provider',
+ 'value': 'edx'
}
],
- "stockrecords": [
+ 'stockrecords': [
{
- "price_currency": "USD",
- "product": 123,
- "partner_sku": "1234ABC",
- "partner": 1,
- "price_excl_tax": "10.00",
- "id": 123
+ 'price_currency': 'USD',
+ 'product': 123,
+ 'partner_sku': '1234ABC',
+ 'partner': 1,
+ 'price_excl_tax': '10.00',
+ 'id': 123
}
],
- "product_class": "Seat",
- "title": "Dummy title",
- "url": "https://ecom.edx.org/api/v2/products/123/",
- "price": "10.00",
- "expires": null,
- "is_available_to_buy": true,
- "id": 123,
- "structure": "child"
+ 'product_class': 'Seat',
+ 'title': 'Dummy title',
+ 'url': 'https://ecom.edx.org/api/v2/products/123/',
+ 'price': '10.00',
+ 'expires': null,
+ 'is_available_to_buy': true,
+ 'id': 123,
+ 'structure': 'child'
},
- "line_price_excl_tax": "10.00",
- "description": "dummy description",
- "title": "dummy title",
- "quantity": 1
+ 'line_price_excl_tax': '10.00',
+ 'description': 'dummy description',
+ 'title': 'dummy title',
+ 'quantity': 1
}
],
- "number": "EDX-123456",
- "date_placed": "2016-01-01T01:01:01Z",
- "currency": "USD",
- "total_excl_tax": "10.00"
+ 'number': 'EDX-123456',
+ 'date_placed': '2016-01-01T01:01:01Z',
+ 'currency': 'USD',
+ 'total_excl_tax': '10.00'
};
providerResponseData = {
- "id": "edx",
- "display_name": "edX",
- "url": "http://www.edx.org",
- "status_url": "http://www.edx.org/status",
- "description": "Nothing",
- "enable_integration": false,
- "fulfillment_instructions": "",
- "thumbnail_url": "http://edx.org/thumbnail.png"
+ 'id': 'edx',
+ 'display_name': 'edX',
+ 'url': 'http://www.edx.org',
+ 'status_url': 'http://www.edx.org/status',
+ 'description': 'Nothing',
+ 'enable_integration': false,
+ 'fulfillment_instructions': '',
+ 'thumbnail_url': 'http://edx.org/thumbnail.png'
};
courseResponseData = {
- "id": "course-v1:edx+dummy+2015_T3",
- "name": "receipt test",
- "category": "course",
- "org": "edx",
- "run": "2015_T2",
- "course": "CS420",
- "uri": "http://test.com/api/courses/v1/courses/course-v1:edx+dummy+2015_T3/",
- "image_url": "/test.jpg",
- "start": "2030-01-01T00:00:00Z",
- "end": null
+ 'id': 'course-v1:edx+dummy+2015_T3',
+ 'name': 'receipt test',
+ 'category': 'course',
+ 'org': 'edx',
+ 'run': '2015_T2',
+ 'course': 'CS420',
+ 'uri': 'http://test.com/api/courses/v1/courses/course-v1:edx+dummy+2015_T3/',
+ 'image_url': '/test.jpg',
+ 'start': '2030-01-01T00:00:00Z',
+ 'end': null
};
userResponseData = {
- "username": "user-1",
- "name": "full name"
+ 'username': 'user-1',
+ 'name': 'full name'
};
});
@@ -167,7 +167,6 @@ define([
currency: 'USD'
}
);
-
});
it('sends analytic event when non verified receipt is rendered', function() {
@@ -180,7 +179,6 @@ define([
currency: 'USD'
}
);
-
});
it('renders a receipt correctly with Ecommerce Order Number', function() {
@@ -196,7 +194,6 @@ define([
view = mockRender(false, 'True');
expect(view.$('.course_name_placeholder').text()).toContain('receipt test');
});
-
});
}
);
diff --git a/lms/static/js/spec/components/card/card_spec.js b/lms/static/js/spec/components/card/card_spec.js
index 4145f9ee83..284138dc50 100644
--- a/lms/static/js/spec/components/card/card_spec.js
+++ b/lms/static/js/spec/components/card/card_spec.js
@@ -1,4 +1,4 @@
-(function (define) {
+(function(define) {
'use strict';
define(['jquery',
@@ -7,43 +7,42 @@
'js/components/card/views/card'
],
function($, _, Backbone, CardView) {
-
- describe('card component view', function () {
- it('can render itself as a square card', function () {
- var view = new CardView({ configuration: 'square_card' });
+ describe('card component view', function() {
+ it('can render itself as a square card', function() {
+ var view = new CardView({configuration: 'square_card'});
expect(view.$el).toHaveClass('square-card');
expect(view.$el.find('.wrapper-card-meta .action').length).toBe(1);
});
- it('can render itself as a list card', function () {
- var view = new CardView({ configuration: 'list_card' });
+ it('can render itself as a list card', function() {
+ var view = new CardView({configuration: 'list_card'});
expect(view.$el).toHaveClass('list-card');
expect(view.$el.find('.wrapper-card-core .action').length).toBe(1);
});
- it('renders a pennant only if the pennant value is truthy', function () {
- var view = new (CardView.extend({ pennant: '' }))();
+ it('renders a pennant only if the pennant value is truthy', function() {
+ var view = new (CardView.extend({pennant: ''}))();
expect(view.$el.find('.card-type').length).toBe(0);
- view = new (CardView.extend({ pennant: 'Test Pennant' }))();
+ view = new (CardView.extend({pennant: 'Test Pennant'}))();
expect(view.$el.find('.card-type').length).toBe(1);
});
- it('can render child views', function () {
- var testChildView = new (Backbone.View.extend({ className: 'test-view' }))();
+ it('can render child views', function() {
+ var testChildView = new (Backbone.View.extend({className: 'test-view'}))();
spyOn(testChildView, 'render');
- var view = new (CardView.extend({ details: [testChildView] }))();
+ var view = new (CardView.extend({details: [testChildView]}))();
expect(testChildView.render).toHaveBeenCalled();
expect(view.$el.find('.test-view')).toHaveClass('meta-detail');
});
- it('calls action when clicked', function () {
+ it('calls action when clicked', function() {
spyOn(CardView.prototype, 'action');
- var view = new CardView({ configuration: 'square_card' });
+ var view = new CardView({configuration: 'square_card'});
view.$el.find('.action').trigger('click');
expect(view.action).toHaveBeenCalled();
});
- var verifyContent = function (view) {
+ var verifyContent = function(view) {
expect(view.$el).toHaveClass('test-card');
expect(view.$el.find('.card-type').text()).toContain('Pennant');
expect(view.$el.find('.card-title').text()).toContain('A test title');
@@ -53,7 +52,7 @@
expect(view.$el.find('.action').text()).toContain('A test action');
};
- it('can have strings for cardClass, pennant, title, description, and action', function () {
+ it('can have strings for cardClass, pennant, title, description, and action', function() {
var view = new (CardView.extend({
cardClass: 'test-card',
pennant: 'Pennant',
@@ -66,15 +65,15 @@
verifyContent(view);
});
- it('can have functions for cardClass, pennant, title, description, and action', function () {
+ it('can have functions for cardClass, pennant, title, description, and action', function() {
var view = new (CardView.extend({
- cardClass: function () { return 'test-card'; },
- pennant: function () { return 'Pennant'; },
- title: function () { return 'A test title'; },
- description: function () { return 'A test description'; },
- actionClass: function () { return 'test-action'; },
- actionUrl: function () { return 'www.example.com'; },
- actionContent: function () { return 'A test action'; }
+ cardClass: function() { return 'test-card'; },
+ pennant: function() { return 'Pennant'; },
+ title: function() { return 'A test title'; },
+ description: function() { return 'A test description'; },
+ actionClass: function() { return 'test-action'; },
+ actionUrl: function() { return 'www.example.com'; },
+ actionContent: function() { return 'A test action'; }
}));
verifyContent(view);
});
diff --git a/lms/static/js/spec/components/header/header_spec.js b/lms/static/js/spec/components/header/header_spec.js
index 7df8ce8ba6..d66a78b58d 100644
--- a/lms/static/js/spec/components/header/header_spec.js
+++ b/lms/static/js/spec/components/header/header_spec.js
@@ -1,4 +1,4 @@
-(function (define) {
+(function(define) {
'use strict';
define(['jquery',
@@ -7,20 +7,19 @@
'js/components/header/models/header'
],
function($, _, HeaderView, HeaderModel) {
-
- describe('header component view', function () {
+ describe('header component view', function() {
var model, view;
- var testBreadcrumbs = function (breadcrumbs) {
+ var testBreadcrumbs = function(breadcrumbs) {
model.set('breadcrumbs', breadcrumbs);
expect(view.$('nav.breadcrumbs').length).toBe(1);
- _.each(view.$('.nav-item'), function (el, index) {
+ _.each(view.$('.nav-item'), function(el, index) {
expect($(el).attr('href')).toEqual(breadcrumbs[index].url);
expect($(el).text()).toEqual(breadcrumbs[index].title);
});
};
- beforeEach(function () {
+ beforeEach(function() {
model = new HeaderModel({
title: 'Test title',
description: 'Test description'
@@ -30,16 +29,16 @@
});
});
- it('can render itself', function () {
+ it('can render itself', function() {
expect(view.$el.text()).toContain('Test title');
expect(view.$el.text()).toContain('Test description');
});
- it('does not show breadcrumbs by default', function () {
+ it('does not show breadcrumbs by default', function() {
expect(view.$el.html()).not.toContain('
' +
+ "'
);
var certificate_invalidations = new CertificateInvalidationCollection(certificate_invalidations_json, {
@@ -159,19 +158,19 @@ define([
view = new CertificateInvalidationView({collection: certificate_invalidations});
view.render();
- user_name_field = $("#certificate-invalidation-user");
- notes_field = $("#certificate-invalidation-notes");
- invalidate_button = $("#invalidate-certificate");
+ user_name_field = $('#certificate-invalidation-user');
+ notes_field = $('#certificate-invalidation-notes');
+ invalidate_button = $('#invalidate-certificate');
requests = AjaxHelpers.requests(this);
});
- it("verifies view is initialized and rendered successfully", function() {
+ it('verifies view is initialized and rendered successfully', function() {
expect(view).not.toBe(undefined);
expect(view.$el.find('table tbody tr').length).toBe(2);
});
- it("verifies view is rendered on add/remove to collection", function() {
+ it('verifies view is rendered on add/remove to collection', function() {
var user = 'test3',
notes = 'test3 notes',
model = new CertificateInvalidationModel(
@@ -193,27 +192,25 @@ define([
// Verify view is updated
expect(view.$el.find('table tbody tr').length).toBe(2);
-
-
});
- it("verifies view error message on duplicate certificate validation.", function() {
+ it('verifies view error message on duplicate certificate validation.', function() {
$(user_name_field).val(duplicate_user);
$(invalidate_button).click();
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.duplicate_user);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.duplicate_user);
});
- it("verifies view error message on empty username/email field.", function() {
- $(user_name_field).val("");
+ it('verifies view error message on empty username/email field.', function() {
+ $(user_name_field).val('');
$(invalidate_button).click();
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.empty_user_name_email);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.empty_user_name_email);
});
- it("verifies view success message on certificate invalidation.", function() {
+ it('verifies view success message on certificate invalidation.', function() {
$(user_name_field).val(new_user);
- $(notes_field).val("test notes for user test4");
+ $(notes_field).val('test notes for user test4');
$(invalidate_button).click();
AjaxHelpers.respondWithJson(
@@ -222,36 +219,36 @@ define([
id: 4,
user: 'test4',
validated_by: 5,
- created: "Thursday, December 29, 2015",
- notes: "test notes for user test4"
+ created: 'Thursday, December 29, 2015',
+ notes: 'test notes for user test4'
}
);
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.success.saved);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.success.saved);
});
- it("verifies view server error if server returns unknown response.", function() {
+ it('verifies view server error if server returns unknown response.', function() {
$(user_name_field).val(new_user);
- $(notes_field).val("test notes for user test4");
+ $(notes_field).val('test notes for user test4');
$(invalidate_button).click();
// Response with empty body
- AjaxHelpers.respondWithTextError(requests, 400, "");
+ AjaxHelpers.respondWithTextError(requests, 400, '');
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.server_error);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.server_error);
});
- it("verifies certificate re-validation request and success message.", function() {
+ it('verifies certificate re-validation request and success message.', function() {
var user = 'test1',
- re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" +
+ re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" +
user + "') td .re-validate-certificate";
$(re_validate_certificate).click();
AjaxHelpers.respondWithJson(requests, {});
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.success.re_validated);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.success.re_validated);
});
- it("verifies error message from server is displayed.", function() {
+ it('verifies error message from server is displayed.', function() {
var user = 'test1',
re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" +
user + "') td .re-validate-certificate";
@@ -262,9 +259,8 @@ define([
message: messages.error.from_server
});
- expect($("#certificate-invalidation div.message").text()).toEqual(messages.error.from_server);
+ expect($('#certificate-invalidation div.message').text()).toEqual(messages.error.from_server);
});
-
});
}
);
diff --git a/lms/static/js/spec/instructor_dashboard/certificates_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_spec.js
index 4cf8b76867..2dd689f9da 100644
--- a/lms/static/js/spec/instructor_dashboard/certificates_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/certificates_spec.js
@@ -1,12 +1,12 @@
-/*global define, onCertificatesReady */
+/* global define, onCertificatesReady */
define([
- 'jquery',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/instructor_dashboard/certificates'
- ],
+ 'jquery',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/instructor_dashboard/certificates'
+],
function($, AjaxHelpers) {
'use strict';
- describe("edx.instructor_dashboard.certificates.regenerate_certificates", function() {
+ describe('edx.instructor_dashboard.certificates.regenerate_certificates', function() {
var $regenerate_certificates_button = null,
$certificate_regeneration_status = null,
requests = null;
@@ -14,18 +14,18 @@ define([
success_message: 'Certificate regeneration task has been started. ' +
'You can view the status of the generation task in the "Pending Tasks" section.',
error_message: 'Please select one or more certificate statuses that require certificate regeneration.',
- server_error_message: "Error while regenerating certificates. Please try again."
+ server_error_message: 'Error while regenerating certificates. Please try again.'
};
var expected = {
url: 'test/url/',
- postData : [],
+ postData: [],
selected_statuses: ['downloadable', 'error'],
body: 'certificate_statuses=downloadable&certificate_statuses=error'
};
- var select_options = function(option_values){
- $.each(option_values, function(index, element){
- $("#certificate-regenerating-form input[value=" + element + "]").click();
+ var select_options = function(option_values) {
+ $.each(option_values, function(index, element) {
+ $('#certificate-regenerating-form input[value=' + element + ']').click();
});
};
@@ -59,26 +59,26 @@ define([
setFixtures(fixture);
onCertificatesReady();
- $regenerate_certificates_button = $("#btn-start-regenerating-certificates");
- $certificate_regeneration_status = $(".certificate-regeneration-status");
+ $regenerate_certificates_button = $('#btn-start-regenerating-certificates');
+ $certificate_regeneration_status = $('.certificate-regeneration-status');
requests = AjaxHelpers.requests(this);
});
- it("does not regenerate certificates if user cancels operation in confirm popup", function() {
+ it('does not regenerate certificates if user cancels operation in confirm popup', function() {
spyOn(window, 'confirm').and.returnValue(false);
$regenerate_certificates_button.click();
expect(window.confirm).toHaveBeenCalled();
AjaxHelpers.expectNoRequests(requests);
});
- it("sends regenerate certificates request if user accepts operation in confirm popup", function() {
+ it('sends regenerate certificates request if user accepts operation in confirm popup', function() {
spyOn(window, 'confirm').and.returnValue(true);
$regenerate_certificates_button.click();
expect(window.confirm).toHaveBeenCalled();
AjaxHelpers.expectRequest(requests, 'POST', expected.url);
});
- it("sends regenerate certificates request with selected certificate statuses", function() {
+ it('sends regenerate certificates request with selected certificate statuses', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -87,7 +87,7 @@ define([
AjaxHelpers.expectRequest(requests, 'POST', expected.url, expected.body);
});
- it("displays error message in case of server side error", function() {
+ it('displays error message in case of server side error', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -96,7 +96,7 @@ define([
expect($certificate_regeneration_status.text()).toEqual(MESSAGES.server_error_message);
});
- it("displays error message returned by the server in case of unsuccessful request", function() {
+ it('displays error message returned by the server in case of unsuccessful request', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -105,7 +105,7 @@ define([
expect($certificate_regeneration_status.text()).toEqual(MESSAGES.error_message);
});
- it("displays success message returned by the server in case of successful request", function() {
+ it('displays success message returned by the server in case of successful request', function() {
spyOn(window, 'confirm').and.returnValue(true);
select_options(expected.selected_statuses);
@@ -113,7 +113,6 @@ define([
AjaxHelpers.respondWithJson(requests, {message: MESSAGES.success_message, success: true});
expect($certificate_regeneration_status.text()).toEqual(MESSAGES.success_message);
});
-
});
}
);
diff --git a/lms/static/js/spec/instructor_dashboard/data_download_spec.js b/lms/static/js/spec/instructor_dashboard/data_download_spec.js
index d873c3b337..80ad0bdd01 100644
--- a/lms/static/js/spec/instructor_dashboard/data_download_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/data_download_spec.js
@@ -1,11 +1,11 @@
-/*global define */
+/* global define */
define(['jquery',
'coffee/src/instructor_dashboard/data_download',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'slick.grid'],
- function ($, DataDownload, AjaxHelpers) {
+ function($, DataDownload, AjaxHelpers) {
'use strict';
- describe("edx.instructor_dashboard.data_download.DataDownload_Certificate", function() {
+ describe('edx.instructor_dashboard.data_download.DataDownload_Certificate', function() {
var url, data_download_certificate;
beforeEach(function() {
@@ -19,9 +19,9 @@ define(['jquery',
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
var data = {
- 'certificates': [{'course_id':'xyz_test', 'mode':'honor'}],
+ 'certificates': [{'course_id': 'xyz_test', 'mode': 'honor'}],
'queried_features': ['course_id', 'mode'],
- 'feature_names': { 'course_id': 'Course ID', 'mode': ' Mode'}
+ 'feature_names': {'course_id': 'Course ID', 'mode': ' Mode'}
};
data_download_certificate.$list_issued_certificate_table_btn.click();
diff --git a/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js b/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js
index 56a95485ac..4918623a5c 100644
--- a/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/ecommerce_spec.js
@@ -1,18 +1,18 @@
define(['backbone', 'jquery', 'js/instructor_dashboard/ecommerce'],
- function (Backbone, $, ExpiryCouponView) {
+ function(Backbone, $, ExpiryCouponView) {
'use strict';
var expiryCouponView;
- describe("edx.instructor_dashboard.ecommerce.ExpiryCouponView", function() {
+ describe('edx.instructor_dashboard.ecommerce.ExpiryCouponView', function() {
beforeEach(function() {
setFixtures('');
expiryCouponView = new ExpiryCouponView();
});
- it("is defined", function () {
+ it('is defined', function() {
expect(expiryCouponView).toBeDefined();
});
- it("triggers the callback when the checkbox is clicked", function () {
+ it('triggers the callback when the checkbox is clicked', function() {
var target = expiryCouponView.$el.find('input[type="checkbox"]');
spyOn(expiryCouponView, 'clicked');
expiryCouponView.delegateEvents();
@@ -20,15 +20,15 @@ define(['backbone', 'jquery', 'js/instructor_dashboard/ecommerce'],
expect(expiryCouponView.clicked).toHaveBeenCalled();
});
- it("shows the input field when the checkbox is checked", function () {
+ it('shows the input field when the checkbox is checked', function() {
var target = expiryCouponView.$el.find('input[type="checkbox"]');
target.click();
expect(expiryCouponView.$el.find('#coupon_expiration_date').is(':visible')).toBe(true);
});
- it("hides the input field when the checkbox is unchecked", function () {
+ it('hides the input field when the checkbox is unchecked', function() {
var target = expiryCouponView.$el.find('input[type="checkbox"]');
- expect(expiryCouponView.$el.find('#coupon_expiration_date')).toHaveAttr('style','display: none;');
+ expect(expiryCouponView.$el.find('#coupon_expiration_date')).toHaveAttr('style', 'display: none;');
});
});
});
diff --git a/lms/static/js/spec/instructor_dashboard/student_admin_spec.js b/lms/static/js/spec/instructor_dashboard/student_admin_spec.js
index 11223a3422..1edf90b69e 100644
--- a/lms/static/js/spec/instructor_dashboard/student_admin_spec.js
+++ b/lms/static/js/spec/instructor_dashboard/student_admin_spec.js
@@ -1,8 +1,8 @@
define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'],
- function ($, StudentAdmin, AjaxHelpers) {
- //'coffee/src/instructor_dashboard/student_admin'
+ function($, StudentAdmin, AjaxHelpers) {
+ // 'coffee/src/instructor_dashboard/student_admin'
'use strict';
- describe("edx.instructor_dashboard.student_admin.StudentAdmin", function() {
+ describe('edx.instructor_dashboard.student_admin.StudentAdmin', function() {
var studentadmin, dashboard_api_url, unique_student_identifier, alert_msg;
beforeEach(function() {
@@ -15,22 +15,21 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
};
studentadmin = new window.StudentAdmin($('#student_admin'));
dashboard_api_url = '/courses/PU/FSc/2014_T4/instructor/api';
- unique_student_identifier = "test@example.com";
+ unique_student_identifier = 'test@example.com';
alert_msg = '';
spyOn(window, 'alert').and.callFake(function(message) {
alert_msg = message;
});
-
});
it('initiates resetting of entrance exam when button is clicked', function() {
studentadmin.$btn_reset_entrance_exam_attempts.click();
// expect error to be shown since student identifier is not set
- expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext("Please enter a student email address or username."));
+ expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext('Please enter a student email address or username.'));
var success_message = gettext("Entrance exam attempts is being reset for student '{student_id}'.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
@@ -56,7 +55,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when resetting of entrance exam fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_reset_entrance_exam_attempts.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -67,11 +66,11 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error resetting entrance exam attempts for student '{student_id}'. Make sure student identifier is correct.");
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
@@ -79,18 +78,18 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('initiates rescoring of the entrance exam when the button is clicked', function() {
studentadmin.$btn_rescore_entrance_exam.click();
// expect error to be shown since student identifier is not set
- expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext("Please enter a student email address or username."));
+ expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext('Please enter a student email address or username.'));
var success_message = gettext("Started entrance exam rescore task for student '{student_id}'." +
" Click the 'Show Background Task History for Student' button to see the status of the task.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_rescore_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -109,7 +108,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when entrance exam rescoring fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_rescore_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -119,12 +118,12 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error starting a task to rescore entrance exam for student '{student_id}'." +
- " Make sure that entrance exam has problems in it and student identifier is correct.");
+ ' Make sure that entrance exam has problems in it and student identifier is correct.');
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
@@ -136,13 +135,13 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
var success_message = "This student ('{student_id}') will skip the entrance exam.";
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_skip_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var url = dashboard_api_url + '/mark_student_can_skip_entrance_exam';
@@ -160,7 +159,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when skip entrance exam fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_skip_entrance_exam.click();
// Verify that the client contacts the server to start instructor task
var url = dashboard_api_url + '/mark_student_can_skip_entrance_exam';
@@ -169,7 +168,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
}));
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = "An error occurred. Make sure that the student's username or email address is correct and try again.";
expect(studentadmin.$request_response_error_ee.text()).toEqual(error_message);
@@ -178,17 +177,17 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('initiates delete student state for entrance exam when button is clicked', function() {
studentadmin.$btn_delete_entrance_exam_state.click();
// expect error to be shown since student identifier is not set
- expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext("Please enter a student email address or username."));
+ expect(studentadmin.$request_response_error_ee.text()).toEqual(gettext('Please enter a student email address or username.'));
var success_message = gettext("Entrance exam state is being deleted for student '{student_id}'.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_delete_entrance_exam_state.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -208,7 +207,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when delete student state for entrance exam fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_delete_entrance_exam_state.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -219,12 +218,12 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error deleting entrance exam state for student '{student_id}'. " +
- "Make sure student identifier is correct.");
+ 'Make sure student identifier is correct.');
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
@@ -236,13 +235,13 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
var success_message = gettext("Entrance exam state is being deleted for student '{student_id}'.");
var full_success_message = interpolate_text(success_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_entrance_exam_task_history.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -253,17 +252,17 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
// Simulate a success response from the server
AjaxHelpers.respondWithJson(requests, {
- "tasks": [
+ 'tasks': [
{
- "status": "Incomplete",
- "task_type": "rescore_problem",
- "task_id": "9955d413-eac1-441f-978d-27c60dd1c946",
- "created": "2015-02-19T10:59:01+00:00",
- "task_input": "{\"entrance_exam_url\": \"i4x://PU/FSc/chapter/d2204197cce443c4a0d5c852d4e7f638\", \"student\": \"audit\"}",
- "duration_sec": "unknown",
- "task_message": "No status information available",
- "requester": "staff",
- "task_state": "QUEUING"
+ 'status': 'Incomplete',
+ 'task_type': 'rescore_problem',
+ 'task_id': '9955d413-eac1-441f-978d-27c60dd1c946',
+ 'created': '2015-02-19T10:59:01+00:00',
+ 'task_input': '{"entrance_exam_url": "i4x://PU/FSc/chapter/d2204197cce443c4a0d5c852d4e7f638", "student": "audit"}',
+ 'duration_sec': 'unknown',
+ 'task_message': 'No status information available',
+ 'requester': 'staff',
+ 'task_state': 'QUEUING'
}
]
});
@@ -273,7 +272,7 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
it('shows an error when listing entrance exam task history fails', function() {
// Spy on AJAX requests
var requests = AjaxHelpers.requests(this);
- studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier)
+ studentadmin.$field_entrance_exam_student_select_grade.val(unique_student_identifier);
studentadmin.$btn_entrance_exam_task_history.click();
// Verify that the client contacts the server to start instructor task
var params = $.param({
@@ -283,15 +282,14 @@ define(['jquery', 'coffee/src/instructor_dashboard/student_admin', 'edx-ui-toolk
AjaxHelpers.expectPostRequest(requests, url, params);
// Simulate an error response from the server
- AjaxHelpers.respondWithError(requests, 400,{});
+ AjaxHelpers.respondWithError(requests, 400, {});
var error_message = gettext("Error getting entrance exam task history for student '{student_id}'. " +
- "Make sure student identifier is correct.");
+ 'Make sure student identifier is correct.');
var full_error_message = interpolate_text(error_message, {
- student_id: unique_student_identifier
+ student_id: unique_student_identifier
});
expect(studentadmin.$request_response_error_ee.text()).toEqual(full_error_message);
});
-
});
});
diff --git a/lms/static/js/spec/learner_dashboard/certificate_view_spec.js b/lms/static/js/spec/learner_dashboard/certificate_view_spec.js
index 868ddde4c9..2f2ed20fc9 100644
--- a/lms/static/js/spec/learner_dashboard/certificate_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/certificate_view_spec.js
@@ -1,63 +1,62 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/certificate_view'
- ], function (Backbone, $, CertificateView) {
-
- 'use strict';
- describe('Certificate View', function () {
- var view = null,
- data = {
- context: {
- certificatesData: [
- {
- "display_name": "Testing",
- "credential_url": "https://credentials.stage.edx.org/credentials/dummy-uuid-1/"
- },
- {
- "display_name": "Testing2",
- "credential_url": "https://credentials.stage.edx.org/credentials/dummy-uuid-2/"
- }
- ],
- sampleCertImageSrc: "/images/programs/sample-cert.png"
- }
- };
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/certificate_view'
+], function(Backbone, $, CertificateView) {
+ 'use strict';
+ describe('Certificate View', function() {
+ var view = null,
+ data = {
+ context: {
+ certificatesData: [
+ {
+ 'display_name': 'Testing',
+ 'credential_url': 'https://credentials.stage.edx.org/credentials/dummy-uuid-1/'
+ },
+ {
+ 'display_name': 'Testing2',
+ 'credential_url': 'https://credentials.stage.edx.org/credentials/dummy-uuid-2/'
+ }
+ ],
+ sampleCertImageSrc: '/images/programs/sample-cert.png'
+ }
+ };
- beforeEach(function() {
- setFixtures('');
- view = new CertificateView(data);
- view.render();
- });
-
- afterEach(function() {
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the certificates based on passed in certificates list', function() {
- var $certificates = view.$el.find('.certificate-link');
- expect($certificates.length).toBe(2);
-
- $certificates.each(function(index, el){
- expect($(el).html().trim()).toEqual(data.context.certificatesData[index].display_name);
- expect($(el).attr('href')).toEqual(data.context.certificatesData[index].credential_url);
- });
- expect(view.$el.find('.hd-6').html().trim()).toEqual('Program Certificates');
- expect(view.$el.find('img').attr('src')).toEqual(data.context.sampleCertImageSrc);
- });
-
- it('should display no certificate box if certificates list is empty', function() {
- view.remove();
- setFixtures('');
- view = new CertificateView({
- context: {certificatesData: []}
- });
- view.render();
- expect(view.$('.certificates-list').length).toBe(0);
- });
+ beforeEach(function() {
+ setFixtures('');
+ view = new CertificateView(data);
+ view.render();
});
- }
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the certificates based on passed in certificates list', function() {
+ var $certificates = view.$el.find('.certificate-link');
+ expect($certificates.length).toBe(2);
+
+ $certificates.each(function(index, el) {
+ expect($(el).html().trim()).toEqual(data.context.certificatesData[index].display_name);
+ expect($(el).attr('href')).toEqual(data.context.certificatesData[index].credential_url);
+ });
+ expect(view.$el.find('.hd-6').html().trim()).toEqual('Program Certificates');
+ expect(view.$el.find('img').attr('src')).toEqual(data.context.sampleCertImageSrc);
+ });
+
+ it('should display no certificate box if certificates list is empty', function() {
+ view.remove();
+ setFixtures('');
+ view = new CertificateView({
+ context: {certificatesData: []}
+ });
+ view.render();
+ expect(view.$('.certificates-list').length).toBe(0);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js b/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js
index 277b752509..ee3e0c0cc3 100644
--- a/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/collection_list_view_spec.js
@@ -1,154 +1,153 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/program_card_view',
- 'js/learner_dashboard/collections/program_collection',
- 'js/learner_dashboard/views/collection_list_view',
- 'js/learner_dashboard/collections/program_progress_collection'
- ], function (Backbone, $, ProgramCardView, ProgramCollection, CollectionListView,
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/program_card_view',
+ 'js/learner_dashboard/collections/program_collection',
+ 'js/learner_dashboard/views/collection_list_view',
+ 'js/learner_dashboard/collections/program_progress_collection'
+], function(Backbone, $, ProgramCardView, ProgramCollection, CollectionListView,
ProgressCollection) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Collection List View', function () {
- var view = null,
- programCollection,
- progressCollection,
- context = {
- programsData:[
- {
- category: 'xseries',
- status: 'active',
- subtitle: 'program 1',
- name: 'test program 1',
- organizations: [
- {
- display_name: 'edX',
- key: 'edx'
- }
- ],
- created: '2016-03-03T19:18:50.061136Z',
- modified: '2016-03-25T13:45:21.220732Z',
- marketing_slug: 'p_2?param=haha&test=b',
- id: 146,
- marketing_url: 'http://www.edx.org/xseries/p_2?param=haha&test=b',
- banner_image_urls: {
- w348h116: 'http://www.edx.org/images/org1/test1',
- w435h145: 'http://www.edx.org/images/org1/test2',
- w726h242: 'http://www.edx.org/images/org1/test3'
+ 'use strict';
+ /* jslint maxlen: 500 */
+
+ describe('Collection List View', function() {
+ var view = null,
+ programCollection,
+ progressCollection,
+ context = {
+ programsData: [
+ {
+ category: 'xseries',
+ status: 'active',
+ subtitle: 'program 1',
+ name: 'test program 1',
+ organizations: [
+ {
+ display_name: 'edX',
+ key: 'edx'
}
- },
- {
- category: 'xseries',
- status: 'active',
- subtitle: 'fda',
- name: 'fda',
- organizations: [
- {
- display_name: 'edX',
- key: 'edx'
- }
- ],
- created: '2016-03-09T14:30:41.484848Z',
- modified: '2016-03-09T14:30:52.840898Z',
- marketing_slug: 'gdaf',
- id: 147,
- marketing_url: 'http://www.edx.org/xseries/gdaf',
- banner_image_urls: {
- w348h116: 'http://www.edx.org/images/org2/test1',
- w435h145: 'http://www.edx.org/images/org2/test2',
- w726h242: 'http://www.edx.org/images/org2/test3'
+ ],
+ created: '2016-03-03T19:18:50.061136Z',
+ modified: '2016-03-25T13:45:21.220732Z',
+ marketing_slug: 'p_2?param=haha&test=b',
+ id: 146,
+ marketing_url: 'http://www.edx.org/xseries/p_2?param=haha&test=b',
+ banner_image_urls: {
+ w348h116: 'http://www.edx.org/images/org1/test1',
+ w435h145: 'http://www.edx.org/images/org1/test2',
+ w726h242: 'http://www.edx.org/images/org1/test3'
+ }
+ },
+ {
+ category: 'xseries',
+ status: 'active',
+ subtitle: 'fda',
+ name: 'fda',
+ organizations: [
+ {
+ display_name: 'edX',
+ key: 'edx'
}
+ ],
+ created: '2016-03-09T14:30:41.484848Z',
+ modified: '2016-03-09T14:30:52.840898Z',
+ marketing_slug: 'gdaf',
+ id: 147,
+ marketing_url: 'http://www.edx.org/xseries/gdaf',
+ banner_image_urls: {
+ w348h116: 'http://www.edx.org/images/org2/test1',
+ w435h145: 'http://www.edx.org/images/org2/test2',
+ w726h242: 'http://www.edx.org/images/org2/test3'
}
- ],
- userProgress: [
- {
- id: 146,
- completed: ['courses', 'the', 'user', 'completed'],
- in_progress: ['in', 'progress'],
- not_started : ['courses', 'not', 'yet', 'started']
- },
- {
- id: 147,
- completed: ['Course 1'],
- in_progress: [],
- not_started: ['Course 2', 'Course 3', 'Course 4']
- }
- ]
- };
+ }
+ ],
+ userProgress: [
+ {
+ id: 146,
+ completed: ['courses', 'the', 'user', 'completed'],
+ in_progress: ['in', 'progress'],
+ not_started: ['courses', 'not', 'yet', 'started']
+ },
+ {
+ id: 147,
+ completed: ['Course 1'],
+ in_progress: [],
+ not_started: ['Course 2', 'Course 3', 'Course 4']
+ }
+ ]
+ };
- beforeEach(function() {
- setFixtures('');
- programCollection = new ProgramCollection(context.programsData);
- progressCollection = new ProgressCollection();
- progressCollection.set(context.userProgress);
- context.progressCollection = progressCollection;
-
- view = new CollectionListView({
- el: '.program-cards-container',
- childView: ProgramCardView,
- collection: programCollection,
- context: context
- });
- view.render();
- });
+ beforeEach(function() {
+ setFixtures('');
+ programCollection = new ProgramCollection(context.programsData);
+ progressCollection = new ProgressCollection();
+ progressCollection.set(context.userProgress);
+ context.progressCollection = progressCollection;
- afterEach(function() {
- view.remove();
+ view = new CollectionListView({
+ el: '.program-cards-container',
+ childView: ProgramCardView,
+ collection: programCollection,
+ context: context
});
+ view.render();
+ });
- it('should exist', function() {
- expect(view).toBeDefined();
- });
+ afterEach(function() {
+ view.remove();
+ });
- it('should load the collection items based on passed in collection', function() {
- var $cards = view.$el.find('.program-card');
- expect($cards.length).toBe(2);
- $cards.each(function(index, el){
- expect($(el).find('.title').html().trim()).toEqual(context.programsData[index].name);
- });
- });
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
- it('should display no item if collection is empty', function(){
- var $cards;
- view.remove();
- programCollection = new ProgramCollection([]);
- view = new CollectionListView({
- el: '.program-cards-container',
- childView: ProgramCardView,
- context: {'xseriesUrl': '/programs'},
- collection: programCollection
- });
- view.render();
- $cards = view.$el.find('.program-card');
- expect($cards.length).toBe(0);
- });
- it('should have no title when title not provided', function(){
- var $title;
- setFixtures('');
- view.remove();
- view.render();
- expect(view).toBeDefined();
- $title = view.$el.parent().find('.collection-title');
- expect($title.html()).not.toBeDefined();
- });
- it('should display screen reader header when provided', function(){
- var $title, titleContext = {el:'h2', title:'list start'};
- view.remove();
- setFixtures('');
- programCollection = new ProgramCollection(context.programsData);
- view = new CollectionListView({
- el: '.program-cards-container',
- childView: ProgramCardView,
- context: {'xseriesUrl': '/programs'},
- collection: programCollection,
- titleContext: titleContext
- });
- view.render();
- $title = view.$el.parent().find('.collection-title');
- expect($title.html()).toBe(titleContext.title);
+ it('should load the collection items based on passed in collection', function() {
+ var $cards = view.$el.find('.program-card');
+ expect($cards.length).toBe(2);
+ $cards.each(function(index, el) {
+ expect($(el).find('.title').html().trim()).toEqual(context.programsData[index].name);
});
});
- }
+
+ it('should display no item if collection is empty', function() {
+ var $cards;
+ view.remove();
+ programCollection = new ProgramCollection([]);
+ view = new CollectionListView({
+ el: '.program-cards-container',
+ childView: ProgramCardView,
+ context: {'xseriesUrl': '/programs'},
+ collection: programCollection
+ });
+ view.render();
+ $cards = view.$el.find('.program-card');
+ expect($cards.length).toBe(0);
+ });
+ it('should have no title when title not provided', function() {
+ var $title;
+ setFixtures('');
+ view.remove();
+ view.render();
+ expect(view).toBeDefined();
+ $title = view.$el.parent().find('.collection-title');
+ expect($title.html()).not.toBeDefined();
+ });
+ it('should display screen reader header when provided', function() {
+ var $title, titleContext = {el: 'h2', title: 'list start'};
+ view.remove();
+ setFixtures('');
+ programCollection = new ProgramCollection(context.programsData);
+ view = new CollectionListView({
+ el: '.program-cards-container',
+ childView: ProgramCardView,
+ context: {'xseriesUrl': '/programs'},
+ collection: programCollection,
+ titleContext: titleContext
+ });
+ view.render();
+ $title = view.$el.parent().find('.collection-title');
+ expect($title.html()).toBe(titleContext.title);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/course_card_view_spec.js b/lms/static/js/spec/learner_dashboard/course_card_view_spec.js
index 0917211687..5f89de6298 100644
--- a/lms/static/js/spec/learner_dashboard/course_card_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/course_card_view_spec.js
@@ -1,18 +1,17 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/models/course_card_model',
- 'js/learner_dashboard/views/course_card_view'
- ], function (Backbone, $, CourseCardModel, CourseCardView) {
-
- 'use strict';
-
- describe('Course Card View', function () {
- var view = null,
- courseCardModel,
- context,
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/models/course_card_model',
+ 'js/learner_dashboard/views/course_card_view'
+], function(Backbone, $, CourseCardModel, CourseCardView) {
+ 'use strict';
- setupView = function(data, isEnrolled){
+ describe('Course Card View', function() {
+ var view = null,
+ courseCardModel,
+ context,
+
+ setupView = function(data, isEnrolled) {
var programData = $.extend({}, data);
programData.run_modes[0].is_enrolled = isEnrolled;
@@ -23,8 +22,8 @@ define([
});
},
- validateCourseInfoDisplay = function(){
- //DRY validation for course card in enrolled state
+ validateCourseInfoDisplay = function() {
+ // DRY validation for course card in enrolled state
expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
expect(view.$('.course-details .course-title-link').text().trim()).toEqual(context.display_name);
expect(view.$('.course-details .course-title-link').attr('href')).toEqual(
@@ -35,158 +34,158 @@ define([
.toEqual(context.run_modes[0].start_date + ' - ' + context.run_modes[0].end_date);
};
- beforeEach(function() {
+ beforeEach(function() {
// Redefine this data prior to each test case so that tests can't
// break each other by modifying data copied by reference.
- context = {
- course_modes: [],
- display_name: 'Astrophysics: Exploring Exoplanets',
- key: 'ANU-ASTRO1x',
- organization: {
- display_name: 'Australian National University',
- key: 'ANUx'
- },
- run_modes: [{
- certificate_url: '',
- course_image_url: 'http://test.com/image1',
- course_key: 'course-v1:ANUx+ANU-ASTRO1x+3T2015',
- course_started: true,
- course_url: 'https://courses.example.com/courses/course-v1:edX+DemoX+Demo_Course',
- end_date: 'Jun 13, 2019',
- enrollment_open_date: 'Apr 1, 2016',
- is_course_ended: false,
- is_enrolled: true,
- is_enrollment_open: true,
- marketing_url: 'https://www.example.com/marketing/site',
- mode_slug: 'verified',
- run_key: '2T2016',
- start_date: 'Apr 25, 2016',
- upgrade_url: ''
- }]
- };
+ context = {
+ course_modes: [],
+ display_name: 'Astrophysics: Exploring Exoplanets',
+ key: 'ANU-ASTRO1x',
+ organization: {
+ display_name: 'Australian National University',
+ key: 'ANUx'
+ },
+ run_modes: [{
+ certificate_url: '',
+ course_image_url: 'http://test.com/image1',
+ course_key: 'course-v1:ANUx+ANU-ASTRO1x+3T2015',
+ course_started: true,
+ course_url: 'https://courses.example.com/courses/course-v1:edX+DemoX+Demo_Course',
+ end_date: 'Jun 13, 2019',
+ enrollment_open_date: 'Apr 1, 2016',
+ is_course_ended: false,
+ is_enrolled: true,
+ is_enrollment_open: true,
+ marketing_url: 'https://www.example.com/marketing/site',
+ mode_slug: 'verified',
+ run_key: '2T2016',
+ start_date: 'Apr 25, 2016',
+ upgrade_url: ''
+ }]
+ };
- setupView(context, false);
+ setupView(context, false);
+ });
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should render the course card based on the data enrolled', function() {
+ view.remove();
+ setupView(context, true);
+ validateCourseInfoDisplay();
+ });
+
+ it('should render the course card based on the data not enrolled', function() {
+ validateCourseInfoDisplay();
+ });
+
+ it('should update render if the course card is_enrolled updated', function() {
+ courseCardModel.set({
+ is_enrolled: true
});
+ validateCourseInfoDisplay();
+ });
- afterEach(function() {
- view.remove();
- });
+ it('should only show certificate status section if a certificate has been earned', function() {
+ var certUrl = 'sample-certificate';
- it('should exist', function() {
- expect(view).toBeDefined();
- });
+ expect(view.$('.certificate-status').length).toEqual(0);
+ view.remove();
- it('should render the course card based on the data enrolled', function() {
- view.remove();
- setupView(context, true);
- validateCourseInfoDisplay();
- });
+ context.run_modes[0].certificate_url = certUrl;
+ setupView(context, false);
+ expect(view.$('.certificate-status').length).toEqual(1);
+ expect(view.$('.certificate-status .cta-secondary').attr('href')).toEqual(certUrl);
+ });
- it('should render the course card based on the data not enrolled', function() {
- validateCourseInfoDisplay();
- });
+ it('should only show upgrade message section if an upgrade is required', function() {
+ var upgradeUrl = '/path/to/upgrade';
- it('should update render if the course card is_enrolled updated', function() {
- courseCardModel.set({
- is_enrolled: true
- });
- validateCourseInfoDisplay();
- });
+ expect(view.$('.upgrade-message').length).toEqual(0);
+ view.remove();
- it('should only show certificate status section if a certificate has been earned', function() {
- var certUrl = 'sample-certificate';
+ context.run_modes[0].upgrade_url = upgradeUrl;
+ setupView(context, false);
+ expect(view.$('.upgrade-message').length).toEqual(1);
+ expect(view.$('.upgrade-message .cta-primary').attr('href')).toEqual(upgradeUrl);
+ });
- expect(view.$('.certificate-status').length).toEqual(0);
- view.remove();
-
- context.run_modes[0].certificate_url = certUrl;
- setupView(context, false);
- expect(view.$('.certificate-status').length).toEqual(1);
- expect(view.$('.certificate-status .cta-secondary').attr('href')).toEqual(certUrl);
- });
-
- it('should only show upgrade message section if an upgrade is required', function() {
- var upgradeUrl = '/path/to/upgrade';
-
- expect(view.$('.upgrade-message').length).toEqual(0);
- view.remove();
-
- context.run_modes[0].upgrade_url = upgradeUrl;
- setupView(context, false);
- expect(view.$('.upgrade-message').length).toEqual(1);
- expect(view.$('.upgrade-message .cta-primary').attr('href')).toEqual(upgradeUrl);
- });
-
- it('should not show both the upgrade message and certificate status sections', function() {
+ it('should not show both the upgrade message and certificate status sections', function() {
// Verify that no empty elements are left in the DOM.
- context.run_modes[0].upgrade_url = '';
- context.run_modes[0].certificate_url = '';
- setupView(context, false);
- expect(view.$('.upgrade-message').length).toEqual(0);
- expect(view.$('.certificate-status').length).toEqual(0);
- view.remove();
+ context.run_modes[0].upgrade_url = '';
+ context.run_modes[0].certificate_url = '';
+ setupView(context, false);
+ expect(view.$('.upgrade-message').length).toEqual(0);
+ expect(view.$('.certificate-status').length).toEqual(0);
+ view.remove();
// Verify that the upgrade message takes priority.
- context.run_modes[0].upgrade_url = '/path/to/upgrade';
- context.run_modes[0].certificate_url = '/path/to/certificate';
- setupView(context, false);
- expect(view.$('.upgrade-message').length).toEqual(1);
- expect(view.$('.certificate-status').length).toEqual(0);
- });
+ context.run_modes[0].upgrade_url = '/path/to/upgrade';
+ context.run_modes[0].certificate_url = '/path/to/certificate';
+ setupView(context, false);
+ expect(view.$('.upgrade-message').length).toEqual(1);
+ expect(view.$('.certificate-status').length).toEqual(0);
+ });
- it('should show a message if an there is an upcoming course run', function(){
- context.run_modes[0].is_enrollment_open = false;
+ it('should show a message if an there is an upcoming course run', function() {
+ context.run_modes[0].is_enrollment_open = false;
- setupView(context, false);
+ setupView(context, false);
- expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
- expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
- expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
- expect(view.$('.course-details .course-text .run-period').length).toBe(0);
- expect(view.$('.no-action-message').text().trim()).toBe('Coming Soon');
- expect(view.$('.enrollment-open-date').text().trim()).toEqual(
+ expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
+ expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
+ expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
+ expect(view.$('.course-details .course-text .run-period').length).toBe(0);
+ expect(view.$('.no-action-message').text().trim()).toBe('Coming Soon');
+ expect(view.$('.enrollment-open-date').text().trim()).toEqual(
context.run_modes[0].enrollment_open_date
);
- });
+ });
- it('should show a message if there are no known upcoming course runs', function(){
- context.run_modes[0].is_enrollment_open = false;
- context.run_modes[0].is_course_ended = true;
+ it('should show a message if there are no known upcoming course runs', function() {
+ context.run_modes[0].is_enrollment_open = false;
+ context.run_modes[0].is_course_ended = true;
- setupView(context, false);
+ setupView(context, false);
- expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
- expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
- expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
- expect(view.$('.course-details .course-text .run-period').length).toBe(0);
- expect(view.$('.no-action-message').text().trim()).toBe('Not Currently Available');
- expect(view.$('.enrollment-opens').length).toEqual(0);
- });
+ expect(view.$('.header-img').attr('src')).toEqual(context.run_modes[0].course_image_url);
+ expect(view.$('.course-details .course-title').text().trim()).toEqual(context.display_name);
+ expect(view.$('.course-details .course-text .course-key').html()).toEqual(context.key);
+ expect(view.$('.course-details .course-text .run-period').length).toBe(0);
+ expect(view.$('.no-action-message').text().trim()).toBe('Not Currently Available');
+ expect(view.$('.enrollment-opens').length).toEqual(0);
+ });
- it('should link to the marketing site when a URL is available', function(){
- $.each([ '.course-image-link', '.course-title-link' ], function( index, selector ) {
- expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].marketing_url);
- });
- });
-
- it('should link to the course home when no marketing URL is available', function(){
- context.run_modes[0].marketing_url = null;
- setupView(context, false);
-
- $.each([ '.course-image-link', '.course-title-link' ], function( index, selector ) {
- expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].course_url);
- });
- });
-
- it('should not link to the marketing site or the course home if neither URL is available', function(){
- context.run_modes[0].marketing_url = null;
- context.run_modes[0].course_url = null;
- setupView(context, false);
-
- $.each([ '.course-image-link', '.course-title-link' ], function( index, selector ) {
- expect(view.$(selector).length).toEqual(0);
- });
+ it('should link to the marketing site when a URL is available', function() {
+ $.each(['.course-image-link', '.course-title-link'], function(index, selector) {
+ expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].marketing_url);
});
});
- }
+
+ it('should link to the course home when no marketing URL is available', function() {
+ context.run_modes[0].marketing_url = null;
+ setupView(context, false);
+
+ $.each(['.course-image-link', '.course-title-link'], function(index, selector) {
+ expect(view.$(selector).attr('href')).toEqual(context.run_modes[0].course_url);
+ });
+ });
+
+ it('should not link to the marketing site or the course home if neither URL is available', function() {
+ context.run_modes[0].marketing_url = null;
+ context.run_modes[0].course_url = null;
+ setupView(context, false);
+
+ $.each(['.course-image-link', '.course-title-link'], function(index, selector) {
+ expect(view.$(selector).length).toEqual(0);
+ });
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js b/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js
index 6d61720776..95423f2fdb 100644
--- a/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/course_enroll_view_spec.js
@@ -1,243 +1,242 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/models/course_card_model',
- 'js/learner_dashboard/models/course_enroll_model',
- 'js/learner_dashboard/views/course_enroll_view'
- ], function (Backbone, $, CourseCardModel, CourseEnrollModel, CourseEnrollView) {
-
- 'use strict';
-
- describe('Course Enroll View', function () {
- var view = null,
- courseCardModel,
- courseEnrollModel,
- urlModel,
- setupView,
- singleRunModeList,
- multiRunModeList,
- context = {
- display_name: 'Edx Demo course',
- key: 'edX+DemoX+Demo_Course',
- organization: {
- display_name: 'edx.org',
- key: 'edX'
- }
- },
- urls = {
- dashboard_url: '/dashboard',
- id_verification_url: '/verify_student/start_flow/',
- track_selection_url: '/select_track/course/'
- };
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/models/course_card_model',
+ 'js/learner_dashboard/models/course_enroll_model',
+ 'js/learner_dashboard/views/course_enroll_view'
+], function(Backbone, $, CourseCardModel, CourseEnrollModel, CourseEnrollView) {
+ 'use strict';
- beforeEach(function() {
- // Redefine this data prior to each test case so that tests can't
- // break each other by modifying data copied by reference.
- singleRunModeList = [{
- start_date: 'Apr 25, 2016',
- end_date: 'Jun 13, 2016',
- course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
- course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
- course_image_url: 'http://test.com/image1',
- marketing_url: 'http://test.com/image2',
- is_course_ended: false,
- mode_slug: 'audit',
- run_key: '2T2016',
- is_enrolled: false,
- is_enrollment_open: true
- }];
-
- multiRunModeList = [{
- start_date: 'May 21, 2015',
- end_date: 'Sep 21, 2015',
- course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
- course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
- course_image_url: 'http://test.com/run_2_image_1',
- marketing_url: 'http://test.com/run_2_image_2',
- mode_slug: 'verified',
- is_course_ended: false,
- run_key: '1T2015',
- is_enrolled: false,
- is_enrollment_open: true,
- },{
- start_date: 'Sep 22, 2015',
- end_date: 'Dec 28, 2015',
- course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
- course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
- course_image_url: 'http://test.com/run_3_image_1',
- marketing_url: 'http://test.com/run_3_image_2',
- is_course_ended: false,
- mode_slug: 'verified',
- run_key: '2T2015',
- is_enrolled: false,
- is_enrollment_open: true
- }];
- });
-
- setupView = function(runModes, urls){
- context.run_modes = runModes;
- setFixtures('');
- courseCardModel = new CourseCardModel(context);
- courseEnrollModel = new CourseEnrollModel({}, {
- courseId: courseCardModel.get('course_key')
- });
- if(urls){
- urlModel = new Backbone.Model(urls);
+ describe('Course Enroll View', function() {
+ var view = null,
+ courseCardModel,
+ courseEnrollModel,
+ urlModel,
+ setupView,
+ singleRunModeList,
+ multiRunModeList,
+ context = {
+ display_name: 'Edx Demo course',
+ key: 'edX+DemoX+Demo_Course',
+ organization: {
+ display_name: 'edx.org',
+ key: 'edX'
}
- view = new CourseEnrollView({
- $parentEl: $('.course-actions'),
- model: courseCardModel,
- enrollModel: courseEnrollModel,
- urlModel: urlModel
- });
+ },
+ urls = {
+ dashboard_url: '/dashboard',
+ id_verification_url: '/verify_student/start_flow/',
+ track_selection_url: '/select_track/course/'
};
- afterEach(function() {
- view.remove();
- urlModel = null;
- courseCardModel = null;
- courseEnrollModel = null;
- });
+ beforeEach(function() {
+ // Redefine this data prior to each test case so that tests can't
+ // break each other by modifying data copied by reference.
+ singleRunModeList = [{
+ start_date: 'Apr 25, 2016',
+ end_date: 'Jun 13, 2016',
+ course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
+ course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
+ course_image_url: 'http://test.com/image1',
+ marketing_url: 'http://test.com/image2',
+ is_course_ended: false,
+ mode_slug: 'audit',
+ run_key: '2T2016',
+ is_enrolled: false,
+ is_enrollment_open: true
+ }];
- it('should exist', function() {
- setupView(singleRunModeList);
- expect(view).toBeDefined();
- });
-
- it('should render the course enroll view based on not enrolled data', function() {
- setupView(singleRunModeList);
- expect(view.$('.enrollment-info').html().trim()).toEqual('not enrolled');
- expect(view.$('.enroll-button').text().trim()).toEqual('Enroll Now');
- expect(view.$('.run-select').length).toBe(0);
- });
-
- it('should render the course enroll view based on enrolled data', function(){
- singleRunModeList[0].is_enrolled = true;
-
- setupView(singleRunModeList);
-
- expect(view.$('.enrollment-info').html().trim()).toEqual('enrolled');
- expect(view.$('.view-course-link').attr('href')).toEqual(context.run_modes[0].course_url);
- expect(view.$('.view-course-link').text().trim()).toEqual('View Course');
- expect(view.$('.run-select').length).toBe(0);
- });
-
- it('should allow the learner to view an archived course', function(){
- // Regression test for ECOM-4974.
- singleRunModeList[0].is_enrolled = true;
- singleRunModeList[0].is_enrollment_open = false;
- singleRunModeList[0].is_course_ended = true;
-
- setupView(singleRunModeList);
-
- expect(view.$('.view-course-link').text().trim()).toEqual('View Archived Course');
- });
-
- it('should not render anything if run modes is empty', function(){
- setupView([]);
- expect(view.$('.enrollment-info').length).toBe(0);
- expect(view.$('.run-select').length).toBe(0);
- expect(view.$('.enroll-button').length).toBe(0);
- });
-
- it('should render run selection drop down if mulitple run available', function(){
- setupView(multiRunModeList);
- expect(view.$('.run-select').length).toBe(1);
- expect(view.$('.run-select').val()).toEqual('');
- expect(view.$('.run-select option').length).toBe(3);
- });
-
- it('should switch run context if dropdown selection changed', function(){
- setupView(multiRunModeList);
- spyOn(courseCardModel, 'updateRun').and.callThrough();
- expect(view.$('.run-select').val()).toEqual('');
- view.$('.run-select').val(multiRunModeList[1].run_key);
- view.$('.run-select').trigger("change");
- expect(view.$('.run-select').val()).toEqual(multiRunModeList[1].run_key);
- expect(courseCardModel.updateRun)
- .toHaveBeenCalledWith(multiRunModeList[1].run_key);
- expect(courseCardModel.get('run_key')).toEqual(multiRunModeList[1].run_key);
- });
-
- it('should enroll learner when enroll button clicked', function(){
- setupView(singleRunModeList);
- expect(view.$('.enroll-button').length).toBe(1);
- spyOn(courseEnrollModel, 'save');
- view.$('.enroll-button').click();
- expect(courseEnrollModel.save).toHaveBeenCalled();
- });
-
- it('should enroll learner into the updated run with button click', function(){
- setupView(multiRunModeList);
- spyOn(courseEnrollModel, 'save');
- view.$('.run-select').val(multiRunModeList[1].run_key);
- view.$('.run-select').trigger("change");
- view.$('.enroll-button').click();
- expect(courseEnrollModel.save).toHaveBeenCalled();
- });
-
- it('should redirect to trackSelectionUrl when enrollment success for audit track', function(){
- singleRunModeList[0].is_enrolled = false;
- singleRunModeList[0].mode_slug = 'audit';
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollSuccess();
- expect(view.redirect).toHaveBeenCalledWith(
- view.trackSelectionUrl + courseCardModel.get('course_key'));
- });
-
-
- it('should redirect when enrollment success for no track', function(){
- singleRunModeList[0].is_enrolled = false;
- singleRunModeList[0].mode_slug = null;
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollSuccess();
- expect(view.redirect).toHaveBeenCalledWith(
- view.trackSelectionUrl + courseCardModel.get('course_key'));
- });
-
- it('should not redirect when urls not provided', function(){
- singleRunModeList[0].is_enrolled = false;
- singleRunModeList[0].mode_slug = 'verified';
- setupView(singleRunModeList);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.verificationUrl).not.toBeDefined();
- expect(view.dashboardUrl).not.toBeDefined();
- expect(view.trackSelectionUrl).not.toBeDefined();
- spyOn(view, 'redirect');
- view.enrollSuccess();
- expect(view.redirect).not.toHaveBeenCalled();
- });
-
- it('should redirect to track selection on error', function(){
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollError(courseEnrollModel, {status: 500});
- expect(view.redirect).toHaveBeenCalledWith(
- view.trackSelectionUrl + courseCardModel.get('course_key'));
- });
-
- it('should redirect to login on 403 error', function(){
- var response = {
- status: 403,
- responseJSON:{
- user_message_url: 'test_url/haha'
- }};
- setupView(singleRunModeList, urls);
- expect(view.$('.enroll-button').length).toBe(1);
- expect(view.trackSelectionUrl).toBeDefined();
- spyOn(view, 'redirect');
- view.enrollError(courseEnrollModel, response);
- expect(view.redirect).toHaveBeenCalledWith(
- response.responseJSON.user_message_url);
- });
+ multiRunModeList = [{
+ start_date: 'May 21, 2015',
+ end_date: 'Sep 21, 2015',
+ course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
+ course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
+ course_image_url: 'http://test.com/run_2_image_1',
+ marketing_url: 'http://test.com/run_2_image_2',
+ mode_slug: 'verified',
+ is_course_ended: false,
+ run_key: '1T2015',
+ is_enrolled: false,
+ is_enrollment_open: true
+ }, {
+ start_date: 'Sep 22, 2015',
+ end_date: 'Dec 28, 2015',
+ course_key: 'course-v1:course-v1:edX+DemoX+Demo_Course',
+ course_url: 'http://localhost:8000/courses/course-v1:edX+DemoX+Demo_Course/info',
+ course_image_url: 'http://test.com/run_3_image_1',
+ marketing_url: 'http://test.com/run_3_image_2',
+ is_course_ended: false,
+ mode_slug: 'verified',
+ run_key: '2T2015',
+ is_enrolled: false,
+ is_enrollment_open: true
+ }];
});
- }
+
+ setupView = function(runModes, urls) {
+ context.run_modes = runModes;
+ setFixtures('');
+ courseCardModel = new CourseCardModel(context);
+ courseEnrollModel = new CourseEnrollModel({}, {
+ courseId: courseCardModel.get('course_key')
+ });
+ if (urls) {
+ urlModel = new Backbone.Model(urls);
+ }
+ view = new CourseEnrollView({
+ $parentEl: $('.course-actions'),
+ model: courseCardModel,
+ enrollModel: courseEnrollModel,
+ urlModel: urlModel
+ });
+ };
+
+ afterEach(function() {
+ view.remove();
+ urlModel = null;
+ courseCardModel = null;
+ courseEnrollModel = null;
+ });
+
+ it('should exist', function() {
+ setupView(singleRunModeList);
+ expect(view).toBeDefined();
+ });
+
+ it('should render the course enroll view based on not enrolled data', function() {
+ setupView(singleRunModeList);
+ expect(view.$('.enrollment-info').html().trim()).toEqual('not enrolled');
+ expect(view.$('.enroll-button').text().trim()).toEqual('Enroll Now');
+ expect(view.$('.run-select').length).toBe(0);
+ });
+
+ it('should render the course enroll view based on enrolled data', function() {
+ singleRunModeList[0].is_enrolled = true;
+
+ setupView(singleRunModeList);
+
+ expect(view.$('.enrollment-info').html().trim()).toEqual('enrolled');
+ expect(view.$('.view-course-link').attr('href')).toEqual(context.run_modes[0].course_url);
+ expect(view.$('.view-course-link').text().trim()).toEqual('View Course');
+ expect(view.$('.run-select').length).toBe(0);
+ });
+
+ it('should allow the learner to view an archived course', function() {
+ // Regression test for ECOM-4974.
+ singleRunModeList[0].is_enrolled = true;
+ singleRunModeList[0].is_enrollment_open = false;
+ singleRunModeList[0].is_course_ended = true;
+
+ setupView(singleRunModeList);
+
+ expect(view.$('.view-course-link').text().trim()).toEqual('View Archived Course');
+ });
+
+ it('should not render anything if run modes is empty', function() {
+ setupView([]);
+ expect(view.$('.enrollment-info').length).toBe(0);
+ expect(view.$('.run-select').length).toBe(0);
+ expect(view.$('.enroll-button').length).toBe(0);
+ });
+
+ it('should render run selection drop down if mulitple run available', function() {
+ setupView(multiRunModeList);
+ expect(view.$('.run-select').length).toBe(1);
+ expect(view.$('.run-select').val()).toEqual('');
+ expect(view.$('.run-select option').length).toBe(3);
+ });
+
+ it('should switch run context if dropdown selection changed', function() {
+ setupView(multiRunModeList);
+ spyOn(courseCardModel, 'updateRun').and.callThrough();
+ expect(view.$('.run-select').val()).toEqual('');
+ view.$('.run-select').val(multiRunModeList[1].run_key);
+ view.$('.run-select').trigger('change');
+ expect(view.$('.run-select').val()).toEqual(multiRunModeList[1].run_key);
+ expect(courseCardModel.updateRun)
+ .toHaveBeenCalledWith(multiRunModeList[1].run_key);
+ expect(courseCardModel.get('run_key')).toEqual(multiRunModeList[1].run_key);
+ });
+
+ it('should enroll learner when enroll button clicked', function() {
+ setupView(singleRunModeList);
+ expect(view.$('.enroll-button').length).toBe(1);
+ spyOn(courseEnrollModel, 'save');
+ view.$('.enroll-button').click();
+ expect(courseEnrollModel.save).toHaveBeenCalled();
+ });
+
+ it('should enroll learner into the updated run with button click', function() {
+ setupView(multiRunModeList);
+ spyOn(courseEnrollModel, 'save');
+ view.$('.run-select').val(multiRunModeList[1].run_key);
+ view.$('.run-select').trigger('change');
+ view.$('.enroll-button').click();
+ expect(courseEnrollModel.save).toHaveBeenCalled();
+ });
+
+ it('should redirect to trackSelectionUrl when enrollment success for audit track', function() {
+ singleRunModeList[0].is_enrolled = false;
+ singleRunModeList[0].mode_slug = 'audit';
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollSuccess();
+ expect(view.redirect).toHaveBeenCalledWith(
+ view.trackSelectionUrl + courseCardModel.get('course_key'));
+ });
+
+
+ it('should redirect when enrollment success for no track', function() {
+ singleRunModeList[0].is_enrolled = false;
+ singleRunModeList[0].mode_slug = null;
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollSuccess();
+ expect(view.redirect).toHaveBeenCalledWith(
+ view.trackSelectionUrl + courseCardModel.get('course_key'));
+ });
+
+ it('should not redirect when urls not provided', function() {
+ singleRunModeList[0].is_enrolled = false;
+ singleRunModeList[0].mode_slug = 'verified';
+ setupView(singleRunModeList);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.verificationUrl).not.toBeDefined();
+ expect(view.dashboardUrl).not.toBeDefined();
+ expect(view.trackSelectionUrl).not.toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollSuccess();
+ expect(view.redirect).not.toHaveBeenCalled();
+ });
+
+ it('should redirect to track selection on error', function() {
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollError(courseEnrollModel, {status: 500});
+ expect(view.redirect).toHaveBeenCalledWith(
+ view.trackSelectionUrl + courseCardModel.get('course_key'));
+ });
+
+ it('should redirect to login on 403 error', function() {
+ var response = {
+ status: 403,
+ responseJSON: {
+ user_message_url: 'test_url/haha'
+ }};
+ setupView(singleRunModeList, urls);
+ expect(view.$('.enroll-button').length).toBe(1);
+ expect(view.trackSelectionUrl).toBeDefined();
+ spyOn(view, 'redirect');
+ view.enrollError(courseEnrollModel, response);
+ expect(view.redirect).toHaveBeenCalledWith(
+ response.responseJSON.user_message_url);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/program_card_view_spec.js b/lms/static/js/spec/learner_dashboard/program_card_view_spec.js
index 2bd1ed91f7..32603ecb2a 100644
--- a/lms/static/js/spec/learner_dashboard/program_card_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/program_card_view_spec.js
@@ -1,124 +1,122 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/collections/program_progress_collection',
- 'js/learner_dashboard/models/program_model',
- 'js/learner_dashboard/views/program_card_view'
- ], function (Backbone, $, ProgressCollection, ProgramModel, ProgramCardView) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Program card View', function () {
- var view = null,
- programModel,
- program = {
- category: 'FooBar',
- status: 'active',
- subtitle: 'program 1',
- name: 'test program 1',
- organizations: [
- {
- display_name: 'edX',
- key: 'edx'
- }
- ],
- created: '2016-03-03T19:18:50.061136Z',
- modified: '2016-03-25T13:45:21.220732Z',
- marketing_slug: 'p_2?param=haha&test=b',
- id: 146,
- detail_url: 'http://courses.edx.org/dashboard/programs/1/foo',
- banner_image_urls: {
- w348h116: 'http://www.edx.org/images/test1',
- w435h145: 'http://www.edx.org/images/test2',
- w726h242: 'http://www.edx.org/images/test3'
- }
- },
- userProgress = [
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/collections/program_progress_collection',
+ 'js/learner_dashboard/models/program_model',
+ 'js/learner_dashboard/views/program_card_view'
+], function(Backbone, $, ProgressCollection, ProgramModel, ProgramCardView) {
+ 'use strict';
+ /* jslint maxlen: 500 */
+
+ describe('Program card View', function() {
+ var view = null,
+ programModel,
+ program = {
+ category: 'FooBar',
+ status: 'active',
+ subtitle: 'program 1',
+ name: 'test program 1',
+ organizations: [
{
- id: 146,
- completed: ['courses', 'the', 'user', 'completed'],
- in_progress: ['in', 'progress'],
- not_started : ['courses', 'not', 'yet', 'started']
- },
- {
- id: 147,
- completed: ['Course 1'],
- in_progress: [],
- not_started: ['Course 2', 'Course 3', 'Course 4']
+ display_name: 'edX',
+ key: 'edx'
}
],
- progressCollection = new ProgressCollection(),
- cardRenders = function($card) {
- expect($card).toBeDefined();
- expect($card.find('.title').html().trim()).toEqual(program.name);
- expect($card.find('.category span').html().trim()).toEqual(program.category);
- expect($card.find('.organization').html().trim()).toEqual(program.organizations[0].key);
- expect($card.find('.card-link').attr('href')).toEqual(program.detail_url);
- };
+ created: '2016-03-03T19:18:50.061136Z',
+ modified: '2016-03-25T13:45:21.220732Z',
+ marketing_slug: 'p_2?param=haha&test=b',
+ id: 146,
+ detail_url: 'http://courses.edx.org/dashboard/programs/1/foo',
+ banner_image_urls: {
+ w348h116: 'http://www.edx.org/images/test1',
+ w435h145: 'http://www.edx.org/images/test2',
+ w726h242: 'http://www.edx.org/images/test3'
+ }
+ },
+ userProgress = [
+ {
+ id: 146,
+ completed: ['courses', 'the', 'user', 'completed'],
+ in_progress: ['in', 'progress'],
+ not_started: ['courses', 'not', 'yet', 'started']
+ },
+ {
+ id: 147,
+ completed: ['Course 1'],
+ in_progress: [],
+ not_started: ['Course 2', 'Course 3', 'Course 4']
+ }
+ ],
+ progressCollection = new ProgressCollection(),
+ cardRenders = function($card) {
+ expect($card).toBeDefined();
+ expect($card.find('.title').html().trim()).toEqual(program.name);
+ expect($card.find('.category span').html().trim()).toEqual(program.category);
+ expect($card.find('.organization').html().trim()).toEqual(program.organizations[0].key);
+ expect($card.find('.card-link').attr('href')).toEqual(program.detail_url);
+ };
- beforeEach(function() {
- setFixtures('');
- programModel = new ProgramModel(program);
- progressCollection.set(userProgress);
- view = new ProgramCardView({
- model: programModel,
- context: {
- progressCollection: progressCollection
- }
- });
- });
-
- afterEach(function() {
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the program-card based on passed in context', function() {
- cardRenders(view.$el);
- });
-
- it('should call reEvaluatePicture if reLoadBannerImage is called', function(){
- spyOn(view, 'reEvaluatePicture');
- view.reLoadBannerImage();
- expect(view.reEvaluatePicture).toHaveBeenCalled();
- });
-
- it('should handle exceptions from reEvaluatePicture', function(){
- spyOn(view, 'reEvaluatePicture').and.callFake(function(){
- throw {name:'Picturefill had exceptions'};
- });
- view.reLoadBannerImage();
- expect(view.reEvaluatePicture).toHaveBeenCalled();
- expect(view.reLoadBannerImage).not.toThrow('Picturefill had exceptions');
-
- });
-
- it('should calculate the correct percentages for progress bars', function() {
- expect(view.$('.complete').css('width')).toEqual('40%');
- expect(view.$('.in-progress').css('width')).toEqual('20%');
- });
-
- it('should display the correct completed courses message', function() {
- var program = _.findWhere(userProgress, {id: 146}),
- completed = program.completed.length,
- total = completed + program.in_progress.length + program.not_started.length;
-
- expect(view.$('.certificate-status .status-text').not('.secondary').html()).toEqual('You have earned certificates in ' + completed + ' of the ' + total + ' courses so far.');
- });
-
- it('should render cards if there is no progressData', function() {
- view.remove();
- view = new ProgramCardView({
- model: programModel,
- context: {}
- });
- cardRenders(view.$el);
- expect(view.$('.progress').length).toEqual(0);
+ beforeEach(function() {
+ setFixtures('');
+ programModel = new ProgramModel(program);
+ progressCollection.set(userProgress);
+ view = new ProgramCardView({
+ model: programModel,
+ context: {
+ progressCollection: progressCollection
+ }
});
});
- }
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the program-card based on passed in context', function() {
+ cardRenders(view.$el);
+ });
+
+ it('should call reEvaluatePicture if reLoadBannerImage is called', function() {
+ spyOn(view, 'reEvaluatePicture');
+ view.reLoadBannerImage();
+ expect(view.reEvaluatePicture).toHaveBeenCalled();
+ });
+
+ it('should handle exceptions from reEvaluatePicture', function() {
+ spyOn(view, 'reEvaluatePicture').and.callFake(function() {
+ throw {name: 'Picturefill had exceptions'};
+ });
+ view.reLoadBannerImage();
+ expect(view.reEvaluatePicture).toHaveBeenCalled();
+ expect(view.reLoadBannerImage).not.toThrow('Picturefill had exceptions');
+ });
+
+ it('should calculate the correct percentages for progress bars', function() {
+ expect(view.$('.complete').css('width')).toEqual('40%');
+ expect(view.$('.in-progress').css('width')).toEqual('20%');
+ });
+
+ it('should display the correct completed courses message', function() {
+ var program = _.findWhere(userProgress, {id: 146}),
+ completed = program.completed.length,
+ total = completed + program.in_progress.length + program.not_started.length;
+
+ expect(view.$('.certificate-status .status-text').not('.secondary').html()).toEqual('You have earned certificates in ' + completed + ' of the ' + total + ' courses so far.');
+ });
+
+ it('should render cards if there is no progressData', function() {
+ view.remove();
+ view = new ProgramCardView({
+ model: programModel,
+ context: {}
+ });
+ cardRenders(view.$el);
+ expect(view.$('.progress').length).toEqual(0);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/program_details_header_spec.js b/lms/static/js/spec/learner_dashboard/program_details_header_spec.js
index db8c560160..954ea62667 100644
--- a/lms/static/js/spec/learner_dashboard/program_details_header_spec.js
+++ b/lms/static/js/spec/learner_dashboard/program_details_header_spec.js
@@ -1,66 +1,65 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/program_header_view'
- ], function (Backbone, $, ProgramHeaderView) {
-
- 'use strict';
-
- describe('Program Details Header View', function () {
- var view = null,
- context = {
- urls: {
- program_listing_url: '/dashboard/programs'
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/program_header_view'
+], function(Backbone, $, ProgramHeaderView) {
+ 'use strict';
+
+ describe('Program Details Header View', function() {
+ var view = null,
+ context = {
+ urls: {
+ program_listing_url: '/dashboard/programs'
+ },
+ programData: {
+ uuid: '12-ab',
+ name: 'Astrophysics',
+ subtitle: 'Learn contemporary astrophysics from the leaders in the field.',
+ category: 'xseries',
+ organizations: [
+ {
+ display_name: 'Australian National University',
+ img: 'common/test/data/static/picture1.jpg',
+ key: 'ANUx'
+ }
+ ],
+ banner_image_urls: {
+ w1440h480: 'common/test/data/static/picture1.jpg',
+ w726h242: 'common/test/data/static/picture2.jpg',
+ w348h116: 'common/test/data/static/picture3.jpg'
},
- programData: {
- uuid: '12-ab',
- name: 'Astrophysics',
- subtitle: 'Learn contemporary astrophysics from the leaders in the field.',
- category: 'xseries',
- organizations: [
- {
- display_name: 'Australian National University',
- img: 'common/test/data/static/picture1.jpg',
- key: 'ANUx'
- }
- ],
- banner_image_urls: {
- w1440h480: 'common/test/data/static/picture1.jpg',
- w726h242: 'common/test/data/static/picture2.jpg',
- w348h116: 'common/test/data/static/picture3.jpg'
- },
- program_details_url: '/dashboard/programs'
- }
- };
+ program_details_url: '/dashboard/programs'
+ }
+ };
- beforeEach(function() {
- setFixtures('');
- view = new ProgramHeaderView({
- model: new Backbone.Model(context)
- });
- view.render();
+ beforeEach(function() {
+ setFixtures('');
+ view = new ProgramHeaderView({
+ model: new Backbone.Model(context)
});
+ view.render();
+ });
- afterEach(function() {
- view.remove();
- });
+ afterEach(function() {
+ view.remove();
+ });
- it('should exist', function() {
- expect(view).toBeDefined();
- });
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
- it('should render the header based on the passed in model', function() {
- var programListUrl = view.$('.breadcrumb-list .crumb:nth-of-type(2) .crumb-link').attr('href');
+ it('should render the header based on the passed in model', function() {
+ var programListUrl = view.$('.breadcrumb-list .crumb:nth-of-type(2) .crumb-link').attr('href');
- expect(view.$('.title').html()).toEqual(context.programData.name);
- expect(view.$('.subtitle').html()).toEqual(context.programData.subtitle);
- expect(view.$('.org-logo').length).toEqual(context.programData.organizations.length);
- expect(view.$('.org-logo').attr('src')).toEqual(context.programData.organizations[0].img);
- expect(view.$('.org-logo').attr('alt')).toEqual(
+ expect(view.$('.title').html()).toEqual(context.programData.name);
+ expect(view.$('.subtitle').html()).toEqual(context.programData.subtitle);
+ expect(view.$('.org-logo').length).toEqual(context.programData.organizations.length);
+ expect(view.$('.org-logo').attr('src')).toEqual(context.programData.organizations[0].img);
+ expect(view.$('.org-logo').attr('alt')).toEqual(
context.programData.organizations[0].display_name + '\'s logo'
);
- expect(programListUrl).toEqual(context.urls.program_listing_url);
- });
+ expect(programListUrl).toEqual(context.urls.program_listing_url);
});
- }
+ });
+}
);
diff --git a/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js b/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js
index c76b1f7e87..7bc6e9fead 100644
--- a/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js
+++ b/lms/static/js/spec/learner_dashboard/sidebar_view_spec.js
@@ -1,67 +1,65 @@
define([
- 'backbone',
- 'jquery',
- 'js/learner_dashboard/views/sidebar_view'
- ], function (Backbone, $, SidebarView) {
-
- 'use strict';
- /*jslint maxlen: 500 */
-
- describe('Sidebar View', function () {
- var view = null,
- context = {
- marketingUrl: 'https://www.example.org/programs',
- certificatesData: [
- {
- "display_name": "Testing",
- "credential_url": "https://credentials.example.com/credentials/uuid/"
- }
- ],
- sampleCertImageSrc: "/images/programs/sample-cert.png"
- };
+ 'backbone',
+ 'jquery',
+ 'js/learner_dashboard/views/sidebar_view'
+], function(Backbone, $, SidebarView) {
+ 'use strict';
+ /* jslint maxlen: 500 */
- beforeEach(function() {
- setFixtures('');
-
- view = new SidebarView({
- el: '.sidebar',
- context: context
- });
- view.render();
+ describe('Sidebar View', function() {
+ var view = null,
+ context = {
+ marketingUrl: 'https://www.example.org/programs',
+ certificatesData: [
+ {
+ 'display_name': 'Testing',
+ 'credential_url': 'https://credentials.example.com/credentials/uuid/'
+ }
+ ],
+ sampleCertImageSrc: '/images/programs/sample-cert.png'
+ };
+
+ beforeEach(function() {
+ setFixtures('');
+
+ view = new SidebarView({
+ el: '.sidebar',
+ context: context
});
-
- afterEach(function() {
- view.remove();
- });
-
- it('should exist', function() {
- expect(view).toBeDefined();
- });
-
- it('should load the exploration panel given a marketing URL', function() {
- var $sidebar = view.$el;
- expect($sidebar.find('.program-advertise .advertise-message').html().trim())
- .toEqual('Browse recently launched courses and see what\'s new in your favorite subjects');
- expect($sidebar.find('.program-advertise .ad-link a').attr('href')).toEqual(context.marketingUrl);
- });
-
- it('should load the certificates based on passed in certificates list', function() {
- expect(view.$('.certificate-link').length).toBe(1);
- });
-
- it('should not load the advertising panel if no marketing URL is provided', function(){
- var $ad;
- view.remove();
- view = new SidebarView({
- el: '.sidebar',
- context: {certificatesData: []}
- });
- view.render();
- $ad = view.$el.find('.program-advertise');
- expect($ad.length).toBe(0);
- expect(view.$('.certificate-link').length).toBe(0);
- });
-
+ view.render();
});
- }
+
+ afterEach(function() {
+ view.remove();
+ });
+
+ it('should exist', function() {
+ expect(view).toBeDefined();
+ });
+
+ it('should load the exploration panel given a marketing URL', function() {
+ var $sidebar = view.$el;
+ expect($sidebar.find('.program-advertise .advertise-message').html().trim())
+ .toEqual('Browse recently launched courses and see what\'s new in your favorite subjects');
+ expect($sidebar.find('.program-advertise .ad-link a').attr('href')).toEqual(context.marketingUrl);
+ });
+
+ it('should load the certificates based on passed in certificates list', function() {
+ expect(view.$('.certificate-link').length).toBe(1);
+ });
+
+ it('should not load the advertising panel if no marketing URL is provided', function() {
+ var $ad;
+ view.remove();
+ view = new SidebarView({
+ el: '.sidebar',
+ context: {certificatesData: []}
+ });
+ view.render();
+ $ad = view.$el.find('.program-advertise');
+ expect($ad.length).toBe(0);
+ expect(view.$('.certificate-link').length).toBe(0);
+ });
+ });
+}
);
diff --git a/lms/static/js/spec/markdown_editor_spec.js b/lms/static/js/spec/markdown_editor_spec.js
index 674039575b..3ef0494b77 100644
--- a/lms/static/js/spec/markdown_editor_spec.js
+++ b/lms/static/js/spec/markdown_editor_spec.js
@@ -3,47 +3,47 @@ define(['Markdown.Editor'], function(MarkdownEditor) {
describe('Markdown.Editor', function() {
var editor = new MarkdownEditor();
- describe('util.isValidUrl', function () {
- it('should return true for http://example.com', function () {
+ describe('util.isValidUrl', function() {
+ it('should return true for http://example.com', function() {
expect(
editor.util.isValidUrl('http://example.com')
).toBeTruthy();
});
- it('should return true for https://example.com', function () {
+ it('should return true for https://example.com', function() {
expect(
editor.util.isValidUrl('https://example.com')
).toBeTruthy();
});
- it('should return true for ftp://example.com', function () {
+ it('should return true for ftp://example.com', function() {
expect(
editor.util.isValidUrl('ftp://example.com')
).toBeTruthy();
});
- it('should return false for http://', function () {
+ it('should return false for http://', function() {
expect(editor.util.isValidUrl('http://')).toBeFalsy();
});
- it('should return false for https://', function () {
+ it('should return false for https://', function() {
expect(editor.util.isValidUrl('https://')).toBeFalsy();
});
- it('should return false for ftp://', function () {
+ it('should return false for ftp://', function() {
expect(editor.util.isValidUrl('ftp://')).toBeFalsy();
});
- it('should return false for fake://example.com', function () {
+ it('should return false for fake://example.com', function() {
expect(
editor.util.isValidUrl('fakeprotocol://example.com')
).toBeFalsy();
});
- it('should return false for fake://', function () {
+ it('should return false for fake://', function() {
expect(
editor.util.isValidUrl('fakeprotocol://')
).toBeFalsy();
});
- it('should return false for www.noprotocol.com', function () {
+ it('should return false for www.noprotocol.com', function() {
expect(
editor.util.isValidUrl('www.noprotocol.com')
).toBeFalsy();
});
- it('should return false for an empty string', function () {
+ it('should return false for an empty string', function() {
expect(
editor.util.isValidUrl('')
).toBeFalsy();
diff --git a/lms/static/js/spec/navigation_spec.js b/lms/static/js/spec/navigation_spec.js
index 12e2964c59..ccdb529118 100644
--- a/lms/static/js/spec/navigation_spec.js
+++ b/lms/static/js/spec/navigation_spec.js
@@ -5,7 +5,7 @@ define(['jquery', 'js/utils/navigation'], function($) {
var accordion, chapterMenu;
function keyPressEvent(key) {
- return $.Event('keydown', { which: key });
+ return $.Event('keydown', {which: key});
}
beforeEach(function() {
@@ -20,9 +20,7 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
describe('constructor', function() {
-
describe('always', function() {
-
it('ensures accordion is present', function() {
expect(accordion.length).toBe(1);
});
@@ -38,7 +36,6 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
describe('open section with mouse click', function() {
-
it('ensures new section is opened and previous section is closed', function() {
accordion.find('.button-chapter').last().trigger('click');
@@ -58,7 +55,6 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
describe('open section with spacebar', function() {
-
it('ensures new section is opened and previous section is closed', function() {
accordion.find('.button-chapter').last().focus().trigger(keyPressEvent(this.KEY.SPACE));
@@ -78,4 +74,4 @@ define(['jquery', 'js/utils/navigation'], function($) {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/lms/static/js/spec/search/search_spec.js b/lms/static/js/spec/search/search_spec.js
index 5c6685b088..e339eb5950 100644
--- a/lms/static/js/spec/search/search_spec.js
+++ b/lms/static/js/spec/search/search_spec.js
@@ -38,29 +38,26 @@ define([
'use strict';
describe('Search', function() {
- beforeEach(function () {
+ beforeEach(function() {
PageHelpers.preventBackboneChangingUrl();
});
- describe('SearchResult', function () {
-
- beforeEach(function () {
+ describe('SearchResult', function() {
+ beforeEach(function() {
this.result = new SearchResult();
});
- it('has properties', function () {
+ it('has properties', function() {
expect(this.result.get('location')).toBeDefined();
expect(this.result.get('content_type')).toBeDefined();
expect(this.result.get('excerpt')).toBeDefined();
expect(this.result.get('url')).toBeDefined();
});
-
});
- describe('SearchCollection', function () {
-
- beforeEach(function () {
+ describe('SearchCollection', function() {
+ beforeEach(function() {
this.collection = new SearchCollection();
this.onSearch = jasmine.createSpy('onSearch');
@@ -73,21 +70,21 @@ define([
this.collection.on('error', this.onError);
});
- it('sends a request without a course ID', function () {
+ it('sends a request without a course ID', function() {
var collection = new SearchCollection([]);
spyOn($, 'ajax');
collection.performSearch('search string');
expect($.ajax.calls.mostRecent().args[0].url).toEqual('/search/');
});
- it('sends a request with course ID', function () {
- var collection = new SearchCollection([], { courseId: 'edx101' });
+ it('sends a request with course ID', function() {
+ var collection = new SearchCollection([], {courseId: 'edx101'});
spyOn($, 'ajax');
collection.performSearch('search string');
expect($.ajax.calls.mostRecent().args[0].url).toEqual('/search/edx101');
});
- it('sends a request and parses the json result', function () {
+ it('sends a request and parses the json result', function() {
var requests = AjaxHelpers.requests(this);
this.collection.performSearch('search string');
var response = {
@@ -112,7 +109,7 @@ define([
expect(this.collection.first().attributes).toEqual(response.results[0].data);
});
- it('handles errors', function () {
+ it('handles errors', function() {
var requests = AjaxHelpers.requests(this);
this.collection.performSearch('search string');
AjaxHelpers.respondWithError(requests, 500);
@@ -120,19 +117,19 @@ define([
expect(this.onError).toHaveBeenCalled();
});
- it('loads next page', function () {
+ it('loads next page', function() {
var requests = AjaxHelpers.requests(this);
- var response = { total: 35, results: [] };
+ var response = {total: 35, results: []};
this.collection.loadNextPage();
AjaxHelpers.respondWithJson(requests, response);
expect(this.onNext).toHaveBeenCalled();
expect(this.onError).not.toHaveBeenCalled();
});
- it('sends correct paging parameters', function () {
+ it('sends correct paging parameters', function() {
var requests = AjaxHelpers.requests(this);
var searchString = 'search string';
- var response = { total: 52, results: [] };
+ var response = {total: 52, results: []};
this.collection.performSearch(searchString);
AjaxHelpers.respondWithJson(requests, response);
this.collection.loadNextPage();
@@ -145,9 +142,9 @@ define([
expect($.ajax.calls.mostRecent().args[0].data.page_index).toEqual(2);
});
- it('has next page', function () {
+ it('has next page', function() {
var requests = AjaxHelpers.requests(this);
- var response = { total: 35, access_denied_count: 5, results: [] };
+ var response = {total: 35, access_denied_count: 5, results: []};
this.collection.performSearch('search string');
AjaxHelpers.respondWithJson(requests, response);
expect(this.collection.hasNextPage()).toEqual(true);
@@ -156,9 +153,9 @@ define([
expect(this.collection.hasNextPage()).toEqual(false);
});
- it('aborts any previous request', function () {
+ it('aborts any previous request', function() {
var requests = AjaxHelpers.requests(this);
- var response = { total: 35, results: [] };
+ var response = {total: 35, results: []};
this.collection.performSearch('old search');
this.collection.performSearch('new search');
@@ -178,15 +175,14 @@ define([
expect(this.onNext.calls.count()).toEqual(1);
});
- describe('reset state', function () {
-
- beforeEach(function () {
+ describe('reset state', function() {
+ beforeEach(function() {
this.collection.page = 2;
this.collection.totalCount = 35;
this.collection.latestModelsCount = 5;
});
- it('resets state when performing new search', function () {
+ it('resets state when performing new search', function() {
this.collection.performSearch('search string');
expect(this.collection.models.length).toEqual(0);
expect(this.collection.page).toEqual(0);
@@ -194,42 +190,37 @@ define([
expect(this.collection.latestModelsCount).toEqual(0);
});
- it('resets state when canceling a search', function () {
+ it('resets state when canceling a search', function() {
this.collection.cancelSearch();
expect(this.collection.models.length).toEqual(0);
expect(this.collection.page).toEqual(0);
expect(this.collection.totalCount).toEqual(0);
expect(this.collection.latestModelsCount).toEqual(0);
});
-
});
-
});
- describe('SearchRouter', function () {
-
- beforeEach(function () {
+ describe('SearchRouter', function() {
+ beforeEach(function() {
this.router = new SearchRouter();
this.onSearch = jasmine.createSpy('onSearch');
this.router.on('search', this.onSearch);
});
- it ('has a search route', function () {
+ it('has a search route', function() {
expect(this.router.routes['search/:query']).toEqual('search');
});
- it ('triggers a search event', function () {
+ it('triggers a search event', function() {
var query = 'mercury';
this.router.search(query);
expect(this.onSearch).toHaveBeenCalledWith(query);
});
-
});
- describe('SearchItemView', function () {
-
+ describe('SearchItemView', function() {
function beforeEachHelper(SearchItemView) {
TemplateHelpers.installTemplates([
'templates/search/course_search_item',
@@ -252,9 +243,9 @@ define([
url: 'path/to/content'
});
- this.item = new SearchItemView({ model: this.model });
+ this.item = new SearchItemView({model: this.model});
this.item.render();
- this.seqItem = new SearchItemView({ model: this.seqModel });
+ this.seqItem = new SearchItemView({model: this.seqModel});
this.seqItem.render();
}
@@ -277,10 +268,10 @@ define([
}
function logsSearchItemViewEvent() {
- this.model.collection = new SearchCollection([this.model], { course_id: 'edx101' });
+ this.model.collection = new SearchCollection([this.model], {course_id: 'edx101'});
this.item.render();
// Mock the redirect call
- spyOn(this.item, 'redirect').and.callFake( function() {} );
+ spyOn(this.item, 'redirect').and.callFake(function() {});
spyOn(Logger, 'log').and.returnValue($.Deferred().resolve());
this.item.$el.find('a').trigger('click');
expect(this.item.redirect).toHaveBeenCalled();
@@ -288,8 +279,8 @@ define([
expect(this.item.redirect).toHaveBeenCalled();
}
- describe('CourseSearchItemView', function () {
- beforeEach(function () {
+ describe('CourseSearchItemView', function() {
+ beforeEach(function() {
beforeEachHelper.call(this, CourseSearchItemView);
});
it('renders items correctly', rendersItem);
@@ -297,23 +288,21 @@ define([
it('logs view event', logsSearchItemViewEvent);
});
- describe('DashSearchItemView', function () {
- beforeEach(function () {
+ describe('DashSearchItemView', function() {
+ beforeEach(function() {
beforeEachHelper.call(this, DashSearchItemView);
});
it('renders items correctly', rendersItem);
it('renders Sequence items correctly', rendersSequentialItem);
- it('displays course name in breadcrumbs', function () {
+ it('displays course name in breadcrumbs', function() {
expect(this.seqItem.$el.find('.result-course-name')).toContainHtml(this.model.get('course_name'));
});
it('logs view event', logsSearchItemViewEvent);
});
-
});
- describe('SearchForm', function () {
-
+ describe('SearchForm', function() {
function trimsInputString() {
var term = ' search string ';
$('.search-field').val(term);
@@ -361,8 +350,8 @@ define([
expect($('.search-button')).toBeVisible();
}
- describe('CourseSearchForm', function () {
- beforeEach(function () {
+ describe('CourseSearchForm', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/course_search_form.html');
this.form = new CourseSearchForm();
this.onClear = jasmine.createSpy('onClear');
@@ -377,8 +366,8 @@ define([
it('clears search when search box is empty', clearsSearchOnEmpty);
});
- describe('DashSearchForm', function () {
- beforeEach(function () {
+ describe('DashSearchForm', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/dashboard_search_form.html');
this.form = new DashSearchForm();
this.onClear = jasmine.createSpy('onClear');
@@ -392,27 +381,25 @@ define([
it('clears search when clicking on cancel button', clearsSearchOnCancel);
it('clears search when search box is empty', clearsSearchOnEmpty);
});
-
});
- describe('SearchResultsView', function () {
-
- function showsLoadingMessage () {
+ describe('SearchResultsView', function() {
+ function showsLoadingMessage() {
this.resultsView.showLoadingMessage();
expect(this.resultsView.$contentElement).toBeHidden();
expect(this.resultsView.$el).toBeVisible();
expect(this.resultsView.$el).not.toBeEmpty();
}
- function showsErrorMessage () {
+ function showsErrorMessage() {
this.resultsView.showErrorMessage();
expect(this.resultsView.$contentElement).toBeHidden();
expect(this.resultsView.$el).toBeVisible();
expect(this.resultsView.$el).not.toBeEmpty();
}
- function returnsToContent () {
+ function returnsToContent() {
this.resultsView.clear();
expect(this.resultsView.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
expect(this.resultsView.$el).toBeHidden();
@@ -426,7 +413,7 @@ define([
expect(this.resultsView.$el.find('ol')).not.toExist();
}
- function rendersSearchResults () {
+ function rendersSearchResults() {
var searchResults = [{
location: ['section', 'subsection', 'unit'],
url: '/some/url/to/content',
@@ -451,36 +438,36 @@ define([
expect(this.resultsView.$el.find('li').length).toEqual(2);
}
- function showsMoreResultsLink () {
+ function showsMoreResultsLink() {
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return true; };
+ this.collection.hasNextPage = function() { return true; };
this.resultsView.render();
expect(this.resultsView.$el.find('a.search-load-next')[0]).toExist();
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return false; };
+ this.collection.hasNextPage = function() { return false; };
this.resultsView.render();
expect(this.resultsView.$el.find('a.search-load-next')[0]).not.toExist();
}
- function triggersNextPageEvent () {
+ function triggersNextPageEvent() {
var onNext = jasmine.createSpy('onNext');
this.resultsView.on('next', onNext);
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return true; };
+ this.collection.hasNextPage = function() { return true; };
this.resultsView.render();
this.resultsView.$el.find('a.search-load-next').click();
expect(onNext).toHaveBeenCalled();
}
- function showsLoadMoreSpinner () {
+ function showsLoadMoreSpinner() {
this.collection.totalCount = 123;
- this.collection.hasNextPage = function () { return true; };
+ this.collection.hasNextPage = function() { return true; };
this.resultsView.render();
expect(this.resultsView.$el.find('a.search-load-next .icon')).toBeHidden();
this.resultsView.loadNext();
// toBeVisible does not work with inline
- expect(this.resultsView.$el.find('a.search-load-next .icon')).toHaveCss({ 'display': 'inline' });
+ expect(this.resultsView.$el.find('a.search-load-next .icon')).toHaveCss({'display': 'inline'});
this.resultsView.renderNext();
expect(this.resultsView.$el.find('a.search-load-next .icon')).toBeHidden();
}
@@ -503,18 +490,18 @@ define([
]);
var MockCollection = Backbone.Collection.extend({
- hasNextPage: function () {},
+ hasNextPage: function() {},
latestModelsCount: 0,
pageSize: 20,
- latestModels: function () {
+ latestModels: function() {
return SearchCollection.prototype.latestModels.apply(this, arguments);
}
});
this.collection = new MockCollection();
- this.resultsView = new SearchResultsView({ collection: this.collection });
+ this.resultsView = new SearchResultsView({collection: this.collection});
}
- describe('CourseSearchResultsView', function () {
+ describe('CourseSearchResultsView', function() {
beforeEach(function() {
beforeEachHelper.call(this, CourseSearchResultsView);
this.contentElementDisplayValue = 'table-cell';
@@ -529,7 +516,7 @@ define([
it('shows a spinner when loading more results', showsLoadMoreSpinner);
});
- describe('DashSearchResultsView', function () {
+ describe('DashSearchResultsView', function() {
beforeEach(function() {
beforeEachHelper.call(this, DashSearchResultsView);
this.contentElementDisplayValue = 'block';
@@ -542,7 +529,7 @@ define([
it('shows a link to load more results', showsMoreResultsLink);
it('triggers an event for next page', triggersNextPageEvent);
it('shows a spinner when loading more results', showsLoadMoreSpinner);
- it('returns back to courses', function () {
+ it('returns back to courses', function() {
var onReset = jasmine.createSpy('onReset');
this.resultsView.on('reset', onReset);
this.resultsView.render();
@@ -553,13 +540,11 @@ define([
expect(this.resultsView.$el).toBeHidden();
});
});
-
});
- describe('SearchApp', function () {
-
- function showsLoadingMessage () {
+ describe('SearchApp', function() {
+ function showsLoadingMessage() {
$('.search-field').val('search string');
$('.search-button').trigger('click');
expect(this.$contentElement).toBeHidden();
@@ -567,7 +552,7 @@ define([
expect(this.$searchResults).not.toBeEmpty();
}
- function performsSearch () {
+ function performsSearch() {
var requests = AjaxHelpers.requests(this);
$('.search-field').val('search string');
$('.search-button').trigger('click');
@@ -589,7 +574,7 @@ define([
expect(this.$searchResults.find('li').length).toEqual(1);
}
- function showsErrorMessage () {
+ function showsErrorMessage() {
var requests = AjaxHelpers.requests(this);
$('.search-field').val('search string');
$('.search-button').trigger('click');
@@ -597,7 +582,7 @@ define([
expect(this.$searchResults).toContainHtml('There was an error');
}
- function updatesNavigationHistory () {
+ function updatesNavigationHistory() {
$('.search-field').val('edx');
$('.search-button').trigger('click');
expect(Backbone.history.navigate.calls.mostRecent().args[0]).toContain('search/edx');
@@ -605,7 +590,7 @@ define([
expect(Backbone.history.navigate.calls.argsFor(1)[0]).toBe('');
}
- function cancelsSearchRequest () {
+ function cancelsSearchRequest() {
var requests = AjaxHelpers.requests(this);
// send search request to server
$('.search-field').val('search string');
@@ -618,13 +603,13 @@ define([
expect(this.$searchResults).toBeHidden();
}
- function clearsResults () {
+ function clearsResults() {
$('.cancel-button').trigger('click');
expect(this.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
expect(this.$searchResults).toBeHidden();
}
- function loadsNextPage () {
+ function loadsNextPage() {
var requests = AjaxHelpers.requests(this);
var response = {
total: 1337,
@@ -652,14 +637,14 @@ define([
expect(this.$searchResults.find('li').length).toEqual(2);
}
- function navigatesToSearch () {
+ function navigatesToSearch() {
var requests = AjaxHelpers.requests(this);
Backbone.history.start();
Backbone.history.loadUrl('search/query');
expect(requests[0].requestBody).toContain('search_string=query');
}
- function loadTemplates () {
+ function loadTemplates() {
TemplateHelpers.installTemplates([
'templates/search/course_search_item',
'templates/search/dashboard_search_item',
@@ -670,9 +655,8 @@ define([
]);
}
- describe('CourseSearchApp', function () {
-
- beforeEach(function () {
+ describe('CourseSearchApp', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/course_search_form.html');
appendSetFixtures(
'' +
@@ -688,7 +672,7 @@ define([
this.$searchResults = $('.courseware-results');
});
- afterEach(function (){
+ afterEach(function() {
Backbone.history.stop();
});
@@ -700,12 +684,10 @@ define([
it('clears results', clearsResults);
it('loads next page', loadsNextPage);
it('navigates to search', navigatesToSearch);
-
});
- describe('DashSearchApp', function () {
-
- beforeEach(function () {
+ describe('DashSearchApp', function() {
+ beforeEach(function() {
loadFixtures('js/fixtures/search/dashboard_search_form.html');
appendSetFixtures(
'' +
@@ -720,7 +702,7 @@ define([
this.$searchResults = $('#dashboard-search-results');
});
- afterEach(function (){
+ afterEach(function() {
Backbone.history.stop();
});
@@ -732,7 +714,7 @@ define([
it('clears results', clearsResults);
it('loads next page', loadsNextPage);
it('navigates to search', navigatesToSearch);
- it('returns to course list', function () {
+ it('returns to course list', function() {
var requests = AjaxHelpers.requests(this);
$('.search-field').val('search string');
$('.search-button').trigger('click');
@@ -755,10 +737,7 @@ define([
expect(this.$searchResults).toBeHidden();
expect(this.$searchResults).toBeEmpty();
});
-
});
-
});
-
});
});
diff --git a/lms/static/js/spec/shoppingcart/shoppingcart_spec.js b/lms/static/js/spec/shoppingcart/shoppingcart_spec.js
index c9ee98efbb..e600bcc73e 100644
--- a/lms/static/js/spec/shoppingcart/shoppingcart_spec.js
+++ b/lms/static/js/spec/shoppingcart/shoppingcart_spec.js
@@ -2,7 +2,7 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/shoppingcart/sh
function(AjaxHelpers) {
'use strict';
- describe("edx.shoppingcart.showcart.CartView", function() {
+ describe('edx.shoppingcart.showcart.CartView', function() {
var view = null;
var requests = null;
@@ -23,11 +23,11 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/shoppingcart/sh
// Verify that the client contacts the server to
// check for all th valid cart items
AjaxHelpers.expectRequest(
- requests, "GET", "/shoppingcart/verify_cart/"
+ requests, 'GET', '/shoppingcart/verify_cart/'
);
});
- it("cart has invalid items, course enrollment has been closed", function() {
+ it('cart has invalid items, course enrollment has been closed', function() {
// Simulate a response from the server containing the
// parameter 'is_course_enrollment_closed'. This decides that
// do we have all the cart items valid in the cart or not
@@ -38,21 +38,19 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/shoppingcart/sh
expect(view.responseFromServer).toHaveBeenCalled();
var data = view.responseFromServer.calls.mostRecent().args[0];
expect(data.is_course_enrollment_closed).toBe(true);
-
});
- it("cart has all valid items, course enrollment is still open", function() {
+ it('cart has all valid items, course enrollment is still open', function() {
// Simulate a response from the server containing the
// parameter 'is_course_enrollment_closed'. This decides that
// do we have all the cart items valid in the cart or not
- AjaxHelpers.respondWithJson(requests, {
+ AjaxHelpers.respondWithJson(requests, {
is_course_enrollment_closed: false
});
expect(view.responseFromServer).toHaveBeenCalled();
var data = view.responseFromServer.calls.mostRecent().args[0];
expect(data.is_course_enrollment_closed).toBe(false);
-
});
});
}
diff --git a/lms/static/js/spec/staff_debug_actions_spec.js b/lms/static/js/spec/staff_debug_actions_spec.js
index d916e2c12a..05cc047f4f 100644
--- a/lms/static/js/spec/staff_debug_actions_spec.js
+++ b/lms/static/js/spec/staff_debug_actions_spec.js
@@ -1,48 +1,47 @@
define([
- 'backbone',
- 'jquery',
- 'js/staff_debug_actions',
+ 'backbone',
+ 'jquery',
+ 'js/staff_debug_actions',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
- ],
- function (Backbone, $, tmp, AjaxHelpers) {
+],
+ function(Backbone, $, tmp, AjaxHelpers) {
'use strict';
var StaffDebug = window.StaffDebug;
- describe('StaffDebugActions', function () {
+ describe('StaffDebugActions', function() {
var location = 'i4x://edX/Open_DemoX/edx_demo_course/problem/test_loc';
var locationName = 'test_loc';
var fixture_id = 'sd_fu_' + locationName;
- var fixture = $('', { id: fixture_id, placeholder: "userman" });
+ var fixture = $('', {id: fixture_id, placeholder: 'userman'});
var escapableLocationName = 'test\.\*\+\?\^\:\$\{\}\(\)\|\]\[loc';
var escapableFixture_id = 'sd_fu_' + escapableLocationName;
- var escapableFixture = $('', {id: escapableFixture_id, placeholder: "userman"});
+ var escapableFixture = $('', {id: escapableFixture_id, placeholder: 'userman'});
var esclocationName = 'P2:problem_1';
- var escapableId = 'result_' + esclocationName;
+ var escapableId = 'result_' + esclocationName;
var escapableResultArea = $('', {id: escapableId});
- describe('get_url ', function () {
- it('defines url to courseware ajax entry point', function () {
- spyOn(StaffDebug, "get_current_url")
- .and.returnValue("/courses/edX/Open_DemoX/edx_demo_course/courseware/stuff");
+ describe('get_url ', function() {
+ it('defines url to courseware ajax entry point', function() {
+ spyOn(StaffDebug, 'get_current_url')
+ .and.returnValue('/courses/edX/Open_DemoX/edx_demo_course/courseware/stuff');
expect(StaffDebug.get_url('rescore_problem'))
.toBe('/courses/edX/Open_DemoX/edx_demo_course/instructor/api/rescore_problem');
});
});
- describe('sanitize_string', function () {
- it('escapes escapable characters in a string', function () {
+ describe('sanitize_string', function() {
+ it('escapes escapable characters in a string', function() {
expect(StaffDebug.sanitized_string('.*+?^:${}()|][')).toBe('\\.\\*\\+\\?\\^\\:\\$\\{\\}\\(\\)\\|\\]\\[');
});
});
- describe('get_user', function () {
-
- it('gets the placeholder username if input field is empty', function () {
+ describe('get_user', function() {
+ it('gets the placeholder username if input field is empty', function() {
$('body').append(fixture);
expect(StaffDebug.get_user(locationName)).toBe('userman');
$('#' + fixture_id).remove();
});
- it('gets a filled in name if there is one', function () {
+ it('gets a filled in name if there is one', function() {
$('body').append(fixture);
$('#' + fixture_id).val('notuserman');
expect(StaffDebug.get_user(locationName)).toBe('notuserman');
@@ -56,13 +55,13 @@ define([
$("input[id^='sd_fu_']").remove();
});
});
- describe('do_idash_action success', function () {
- it('adds a success message to the results element after using an action', function () {
+ describe('do_idash_action success', function() {
+ it('adds a success message to the results element after using an action', function() {
$('body').append(escapableResultArea);
var requests = AjaxHelpers.requests(this);
var action = {
locationName: esclocationName,
- success_msg: 'Successfully reset the attempts for user userman',
+ success_msg: 'Successfully reset the attempts for user userman'
};
StaffDebug.do_idash_action(action);
AjaxHelpers.respondWithJson(requests, action);
@@ -70,22 +69,22 @@ define([
$('#result_' + locationName).remove();
});
});
- describe('do_idash_action error', function () {
- it('adds a failure message to the results element after using an action', function () {
+ describe('do_idash_action error', function() {
+ it('adds a failure message to the results element after using an action', function() {
$('body').append(escapableResultArea);
var requests = AjaxHelpers.requests(this);
var action = {
locationName: esclocationName,
- error_msg: 'Failed to reset attempts.',
+ error_msg: 'Failed to reset attempts.'
};
StaffDebug.do_idash_action(action);
AjaxHelpers.respondWithError(requests);
expect($('#idash_msg').text()).toBe('Failed to reset attempts. ');
$('#result_' + locationName).remove();
});
- });
- describe('reset', function () {
- it('makes an ajax call with the expected parameters', function () {
+ });
+ describe('reset', function() {
+ it('makes an ajax call with the expected parameters', function() {
$('body').append(fixture);
spyOn($, 'ajax');
@@ -103,8 +102,8 @@ define([
$('#' + fixture_id).remove();
});
});
- describe('sdelete', function () {
- it('makes an ajax call with the expected parameters', function () {
+ describe('sdelete', function() {
+ it('makes an ajax call with the expected parameters', function() {
$('body').append(fixture);
spyOn($, 'ajax');
@@ -123,8 +122,8 @@ define([
$('#' + fixture_id).remove();
});
});
- describe('rescore', function () {
- it('makes an ajax call with the expected parameters', function () {
+ describe('rescore', function() {
+ it('makes an ajax call with the expected parameters', function() {
$('body').append(fixture);
spyOn($, 'ajax');
@@ -143,4 +142,4 @@ define([
});
});
});
- });
\ No newline at end of file
+ });
diff --git a/lms/static/js/spec/student_account/access_spec.js b/lms/static/js/spec/student_account/access_spec.js
index 6a2cc49608..66ddf2705a 100644
--- a/lms/static/js/spec/student_account/access_spec.js
+++ b/lms/static/js/spec/student_account/access_spec.js
@@ -1,232 +1,230 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/views/AccessView',
- 'js/student_account/views/FormView',
- 'js/student_account/enrollment',
- 'js/student_account/shoppingcart',
- 'js/student_account/emailoptin'
- ],
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/views/AccessView',
+ 'js/student_account/views/FormView',
+ 'js/student_account/enrollment',
+ 'js/student_account/shoppingcart',
+ 'js/student_account/emailoptin'
+ ],
function($, _, Backbone, TemplateHelpers, AjaxHelpers, AccessView, FormView, EnrollmentInterface,
ShoppingCartInterface) {
-
- describe('edx.student.account.AccessView', function() {
- var requests = null,
- view = null,
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/submit',
- fields: [
- {
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'text',
- required: true,
- placeholder: 'xsy@edx.org',
- instructions: 'Enter your email here.',
- restrictions: {}
- },
- {
- name: 'username',
- label: 'Username',
- defaultValue: '',
- type: 'text',
- required: true,
- placeholder: 'Xsy',
- instructions: 'Enter your username here.',
- restrictions: {
- max_length: 200
+ describe('edx.student.account.AccessView', function() {
+ var requests = null,
+ view = null,
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/submit',
+ fields: [
+ {
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ placeholder: 'xsy@edx.org',
+ instructions: 'Enter your email here.',
+ restrictions: {}
+ },
+ {
+ name: 'username',
+ label: 'Username',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ placeholder: 'Xsy',
+ instructions: 'Enter your username here.',
+ restrictions: {
+ max_length: 200
+ }
}
- }
- ]
- },
- FORWARD_URL = (
+ ]
+ },
+ FORWARD_URL = (
'/account/finish_auth' +
'?course_id=edx%2FDemoX%2FFall' +
'&enrollment_action=enroll' +
'&next=%2Fdashboard'
),
- THIRD_PARTY_COMPLETE_URL = '/auth/complete/provider/';
+ THIRD_PARTY_COMPLETE_URL = '/auth/complete/provider/';
- var ajaxSpyAndInitialize = function(that, mode, nextUrl, finishAuthUrl) {
- var options = {
- initial_mode: mode,
- third_party_auth: {
- currentProvider: null,
- providers: [],
- secondaryProviders: [{name: "provider"}],
- finishAuthUrl: finishAuthUrl
+ var ajaxSpyAndInitialize = function(that, mode, nextUrl, finishAuthUrl) {
+ var options = {
+ initial_mode: mode,
+ third_party_auth: {
+ currentProvider: null,
+ providers: [],
+ secondaryProviders: [{name: 'provider'}],
+ finishAuthUrl: finishAuthUrl
+ },
+ login_redirect_url: nextUrl, // undefined for default
+ platform_name: 'edX',
+ login_form_desc: FORM_DESCRIPTION,
+ registration_form_desc: FORM_DESCRIPTION,
+ password_reset_form_desc: FORM_DESCRIPTION
},
- login_redirect_url: nextUrl, // undefined for default
- platform_name: 'edX',
- login_form_desc: FORM_DESCRIPTION,
- registration_form_desc: FORM_DESCRIPTION,
- password_reset_form_desc: FORM_DESCRIPTION
- },
- $logistrationElement = $('#login-and-registration-container');
+ $logistrationElement = $('#login-and-registration-container');
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
+ requests = AjaxHelpers.requests(that);
// Initialize the access view
- view = new AccessView(_.extend(options, {el: $logistrationElement}));
+ view = new AccessView(_.extend(options, {el: $logistrationElement}));
// Mock the redirect call
- spyOn( view, 'redirect' ).and.callFake( function() {} );
+ spyOn(view, 'redirect').and.callFake(function() {});
// Mock the enrollment and shopping cart interfaces
- spyOn( EnrollmentInterface, 'enroll' ).and.callFake( function() {} );
- spyOn( ShoppingCartInterface, 'addCourseToCart' ).and.callFake( function() {} );
- };
+ spyOn(EnrollmentInterface, 'enroll').and.callFake(function() {});
+ spyOn(ShoppingCartInterface, 'addCourseToCart').and.callFake(function() {});
+ };
- var assertForms = function(visibleType, hiddenType) {
- expect($(visibleType)).not.toHaveClass('hidden');
- expect($(hiddenType)).toHaveClass('hidden');
- expect($('#password-reset-form')).toHaveClass('hidden');
- };
+ var assertForms = function(visibleType, hiddenType) {
+ expect($(visibleType)).not.toHaveClass('hidden');
+ expect($(hiddenType)).toHaveClass('hidden');
+ expect($('#password-reset-form')).toHaveClass('hidden');
+ };
- var selectForm = function(type) {
+ var selectForm = function(type) {
// Create a fake change event to control form toggling
- var changeEvent = $.Event('change');
- changeEvent.currentTarget = $('.form-toggle[data-type="' + type + '"]');
+ var changeEvent = $.Event('change');
+ changeEvent.currentTarget = $('.form-toggle[data-type="' + type + '"]');
// Load form corresponding to the change event
- view.toggleForm(changeEvent);
- };
+ view.toggleForm(changeEvent);
+ };
- beforeEach(function() {
- spyOn(window.history, 'pushState');
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/access');
- TemplateHelpers.installTemplate('templates/student_account/login');
- TemplateHelpers.installTemplate('templates/student_account/register');
- TemplateHelpers.installTemplate('templates/student_account/password_reset');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- TemplateHelpers.installTemplate('templates/student_account/institution_login');
- TemplateHelpers.installTemplate('templates/student_account/institution_register');
+ beforeEach(function() {
+ spyOn(window.history, 'pushState');
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/access');
+ TemplateHelpers.installTemplate('templates/student_account/login');
+ TemplateHelpers.installTemplate('templates/student_account/register');
+ TemplateHelpers.installTemplate('templates/student_account/password_reset');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ TemplateHelpers.installTemplate('templates/student_account/institution_login');
+ TemplateHelpers.installTemplate('templates/student_account/institution_register');
// Stub analytics tracking
- window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
- });
+ window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
+ });
- afterEach(function() {
- Backbone.history.stop();
- });
+ afterEach(function() {
+ Backbone.history.stop();
+ });
- it('can initially display the login form', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('can initially display the login form', function() {
+ ajaxSpyAndInitialize(this, 'login');
/* Verify that the login form is expanded, and that the
/* registration form is collapsed.
*/
- assertForms('#login-form', '#register-form');
- });
+ assertForms('#login-form', '#register-form');
+ });
- it('can initially display the registration form', function() {
- ajaxSpyAndInitialize(this, 'register');
+ it('can initially display the registration form', function() {
+ ajaxSpyAndInitialize(this, 'register');
/* Verify that the registration form is expanded, and that the
/* login form is collapsed.
*/
- assertForms('#register-form', '#login-form');
- });
+ assertForms('#register-form', '#login-form');
+ });
- it('toggles between the login and registration forms', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('toggles between the login and registration forms', function() {
+ ajaxSpyAndInitialize(this, 'login');
// Simulate selection of the registration form
- selectForm('register');
- assertForms('#register-form', '#login-form');
+ selectForm('register');
+ assertForms('#register-form', '#login-form');
// Simulate selection of the login form
- selectForm('login');
- assertForms('#login-form', '#register-form');
- });
+ selectForm('login');
+ assertForms('#login-form', '#register-form');
+ });
- it('toggles between the login and institution login view', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('toggles between the login and institution login view', function() {
+ ajaxSpyAndInitialize(this, 'login');
// Simulate clicking on institution login button
- $('#login-form .button-secondary-login[data-type="institution_login"]').click();
- assertForms('#institution_login-form', '#login-form');
+ $('#login-form .button-secondary-login[data-type="institution_login"]').click();
+ assertForms('#institution_login-form', '#login-form');
// Simulate selection of the login form
- selectForm('login');
- assertForms('#login-form', '#institution_login-form');
- });
+ selectForm('login');
+ assertForms('#login-form', '#institution_login-form');
+ });
- it('toggles between the register and institution register view', function() {
- ajaxSpyAndInitialize(this, 'register');
+ it('toggles between the register and institution register view', function() {
+ ajaxSpyAndInitialize(this, 'register');
// Simulate clicking on institution login button
- $('#register-form .button-secondary-login[data-type="institution_login"]').click();
- assertForms('#institution_login-form', '#register-form');
+ $('#register-form .button-secondary-login[data-type="institution_login"]').click();
+ assertForms('#institution_login-form', '#register-form');
// Simulate selection of the login form
- selectForm('register');
- assertForms('#register-form', '#institution_login-form');
- });
+ selectForm('register');
+ assertForms('#register-form', '#institution_login-form');
+ });
- it('displays the reset password form', function() {
- ajaxSpyAndInitialize(this, 'login');
+ it('displays the reset password form', function() {
+ ajaxSpyAndInitialize(this, 'login');
// Simulate a click on the reset password link
- view.resetPassword();
+ view.resetPassword();
// Verify that the login-anchor is hidden
- expect($("#login-anchor")).toHaveClass('hidden');
+ expect($('#login-anchor')).toHaveClass('hidden');
// Verify that the password reset form is not hidden
- expect($("#password-reset-form")).not.toHaveClass('hidden');
- });
+ expect($('#password-reset-form')).not.toHaveClass('hidden');
+ });
- it('redirects the user to the dashboard on auth complete', function() {
- ajaxSpyAndInitialize(this, 'register');
+ it('redirects the user to the dashboard on auth complete', function() {
+ ajaxSpyAndInitialize(this, 'register');
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Since we did not provide a ?next query param, expect a redirect to the dashboard.
- expect( view.redirect ).toHaveBeenCalledWith( '/dashboard' );
- });
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
- it('proceeds with the third party auth pipeline if active', function() {
- ajaxSpyAndInitialize(this, 'register', '/', THIRD_PARTY_COMPLETE_URL);
+ it('proceeds with the third party auth pipeline if active', function() {
+ ajaxSpyAndInitialize(this, 'register', '/', THIRD_PARTY_COMPLETE_URL);
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Verify that we were redirected
- expect( view.redirect ).toHaveBeenCalledWith( THIRD_PARTY_COMPLETE_URL );
- });
+ expect(view.redirect).toHaveBeenCalledWith(THIRD_PARTY_COMPLETE_URL);
+ });
- it('redirects the user to the next page on auth complete', function() {
+ it('redirects the user to the next page on auth complete', function() {
// The 'next' argument is often used to redirect to the auto-enrollment view
- ajaxSpyAndInitialize(this, 'register', FORWARD_URL);
+ ajaxSpyAndInitialize(this, 'register', FORWARD_URL);
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Verify that we were redirected
- expect( view.redirect ).toHaveBeenCalledWith( FORWARD_URL );
- });
+ expect(view.redirect).toHaveBeenCalledWith(FORWARD_URL);
+ });
- it('ignores redirect to external URLs', function() {
- ajaxSpyAndInitialize(this, 'register', "http://www.example.com");
+ it('ignores redirect to external URLs', function() {
+ ajaxSpyAndInitialize(this, 'register', 'http://www.example.com');
// Trigger auth complete
- view.subview.register.trigger('auth-complete');
+ view.subview.register.trigger('auth-complete');
// Expect that we ignore the external URL and redirect to the dashboard
- expect( view.redirect ).toHaveBeenCalledWith( "/dashboard" );
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
});
-
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/account_settings_factory_spec.js b/lms/static/js/spec/student_account/account_settings_factory_spec.js
index bd661cf30d..58c1554250 100644
--- a/lms/static/js/spec/student_account/account_settings_factory_spec.js
+++ b/lms/static/js/spec/student_account/account_settings_factory_spec.js
@@ -9,12 +9,11 @@ define(['backbone',
'js/student_account/views/account_settings_factory',
'js/student_account/views/account_settings_view'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers, Helpers,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers, Helpers,
AccountSettingsFieldViewSpecHelpers, AccountSettingsPage) {
'use strict';
- describe("edx.user.AccountSettingsFactory", function () {
-
+ describe('edx.user.AccountSettingsFactory', function() {
var FIELDS_DATA = {
'country': {
'options': Helpers.FIELD_OPTIONS
@@ -31,7 +30,7 @@ define(['backbone',
}, 'preferred_language': {
'options': Helpers.FIELD_OPTIONS
}, 'time_zone': {
- 'options': Helpers.FIELD_OPTIONS,
+ 'options': Helpers.FIELD_OPTIONS
}
};
@@ -39,7 +38,7 @@ define(['backbone',
'providers': [
{
'id': 'oa2-network1',
- 'name': "Network1",
+ 'name': 'Network1',
'connected': true,
'accepts_logins': 'true',
'connect_url': 'yetanother1.com/auth/connect',
@@ -47,7 +46,7 @@ define(['backbone',
},
{
'id': 'oa2-network2',
- 'name': "Network2",
+ 'name': 'Network2',
'connected': true,
'accepts_logins': 'true',
'connect_url': 'yetanother2.com/auth/connect',
@@ -65,12 +64,11 @@ define(['backbone',
var requests;
- beforeEach(function () {
+ beforeEach(function() {
setFixtures('
');
});
- it("shows loading error when UserAccountModel fails to load", function() {
-
+ it('shows loading error when UserAccountModel fails to load', function() {
requests = AjaxHelpers.requests(this);
var accountSettingsView = createAccountSettingsPage();
@@ -90,8 +88,7 @@ define(['backbone',
});
- it("shows loading error when UserPreferencesModel fails to load", function() {
-
+ it('shows loading error when UserPreferencesModel fails to load', function() {
requests = AjaxHelpers.requests(this);
var accountSettingsView = createAccountSettingsPage();
@@ -119,8 +116,7 @@ define(['backbone',
Helpers.expectSettingsSectionsButNotFieldsToBeRendered(accountSettingsView);
});
- it("renders fields after the models are successfully fetched", function() {
-
+ it('renders fields after the models are successfully fetched', function() {
requests = AjaxHelpers.requests(this);
var accountSettingsView = createAccountSettingsPage();
@@ -137,7 +133,7 @@ define(['backbone',
Helpers.expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView);
});
- it("expects all fields to behave correctly", function () {
+ it('expects all fields to behave correctly', function() {
var i, view;
requests = AjaxHelpers.requests(this);
@@ -153,7 +149,7 @@ define(['backbone',
expect(sectionsData[0].fields.length).toBe(7);
var textFields = [sectionsData[0].fields[1], sectionsData[0].fields[2]];
- for (i = 0; i < textFields.length ; i++) {
+ for (i = 0; i < textFields.length; i++) {
view = textFields[i].view;
FieldViewsSpecHelpers.verifyTextField(view, {
title: view.options.title,
@@ -162,7 +158,7 @@ define(['backbone',
validValue: 'My Name',
invalidValue1: '',
invalidValue2: '@',
- validationError: "Think again!",
+ validationError: 'Think again!',
defaultValue: ''
}, requests);
}
@@ -182,7 +178,7 @@ define(['backbone',
validValue: Helpers.FIELD_OPTIONS[1][0],
invalidValue1: Helpers.FIELD_OPTIONS[2][0],
invalidValue2: Helpers.FIELD_OPTIONS[3][0],
- validationError: "Nope, this will not do!",
+ validationError: 'Nope, this will not do!',
defaultValue: null
}, requests);
});
diff --git a/lms/static/js/spec/student_account/account_settings_fields_helpers.js b/lms/static/js/spec/student_account/account_settings_fields_helpers.js
index dba80de795..69e20281c9 100644
--- a/lms/static/js/spec/student_account/account_settings_fields_helpers.js
+++ b/lms/static/js/spec/student_account/account_settings_fields_helpers.js
@@ -5,10 +5,10 @@ define(['backbone',
'common/js/spec_helpers/template_helpers',
'js/spec/views/fields_helpers',
'string_utils'],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers) {
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViewsSpecHelpers) {
'use strict';
- var verifyAuthField = function (view, data, requests) {
+ var verifyAuthField = function(view, data, requests) {
var selector = '.u-field-value .u-field-link-title-' + view.options.valueAttribute;
spyOn(view, 'redirect_to');
diff --git a/lms/static/js/spec/student_account/account_settings_fields_spec.js b/lms/static/js/spec/student_account/account_settings_fields_spec.js
index 5c6c5095d6..ca19620440 100644
--- a/lms/static/js/spec/student_account/account_settings_fields_spec.js
+++ b/lms/static/js/spec/student_account/account_settings_fields_spec.js
@@ -9,16 +9,15 @@ define(['backbone',
'js/student_account/views/account_settings_fields',
'js/student_account/models/user_account_model',
'string_utils'],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers,
AccountSettingsFieldViewSpecHelpers, AccountSettingsFieldViews) {
'use strict';
- describe("edx.AccountSettingsFieldViews", function () {
-
+ describe('edx.AccountSettingsFieldViews', function() {
var requests,
timerCallback;
- beforeEach(function () {
+ beforeEach(function() {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.clock().install();
});
@@ -27,7 +26,7 @@ define(['backbone',
jasmine.clock().uninstall();
});
- it("sends request to reset password on clicking link in PasswordFieldView", function() {
+ it('sends request to reset password on clicking link in PasswordFieldView', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(AccountSettingsFieldViews.PasswordFieldView, {
@@ -37,16 +36,16 @@ define(['backbone',
var view = new AccountSettingsFieldViews.PasswordFieldView(fieldData).render();
view.$('.u-field-value > button').click();
- AjaxHelpers.expectRequest(requests, 'POST', '/password_reset', "email=legolas%40woodland.middlearth");
- AjaxHelpers.respondWithJson(requests, {"success": "true"});
+ AjaxHelpers.expectRequest(requests, 'POST', '/password_reset', 'email=legolas%40woodland.middlearth');
+ AjaxHelpers.respondWithJson(requests, {'success': 'true'});
FieldViewsSpecHelpers.expectMessageContains(
view,
"We've sent a message to legolas@woodland.middlearth. " +
- "Click the link in the message to reset your password."
+ 'Click the link in the message to reset your password.'
);
});
- it("sends request to /i18n/setlang/ after changing language preference in LanguagePreferenceFieldView", function() {
+ it('sends request to /i18n/setlang/ after changing language preference in LanguagePreferenceFieldView', function() {
requests = AjaxHelpers.requests(this);
var selector = '.u-field-value > select';
@@ -70,7 +69,7 @@ define(['backbone',
'language=' + data[fieldData.valueAttribute]
);
AjaxHelpers.respondWithNoContent(requests);
- FieldViewsSpecHelpers.expectMessageContains(view, "Your changes have been saved.");
+ FieldViewsSpecHelpers.expectMessageContains(view, 'Your changes have been saved.');
data = {'language': FieldViewsSpecHelpers.SELECT_OPTIONS[1][0]};
view.$(selector).val(data[fieldData.valueAttribute]).change();
@@ -86,11 +85,11 @@ define(['backbone',
AjaxHelpers.respondWithError(requests, 500);
FieldViewsSpecHelpers.expectMessageContains(
view,
- "You must sign out and sign back in before your language changes take effect."
+ 'You must sign out and sign back in before your language changes take effect.'
);
});
- it("reads and saves the value correctly for LanguageProficienciesFieldView", function() {
+ it('reads and saves the value correctly for LanguageProficienciesFieldView', function() {
requests = AjaxHelpers.requests(this);
var selector = '.u-field-value > select';
@@ -111,7 +110,7 @@ define(['backbone',
AjaxHelpers.respondWithNoContent(requests);
});
- it("correctly links and unlinks from AuthFieldView", function() {
+ it('correctly links and unlinks from AuthFieldView', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.LinkFieldView, {
diff --git a/lms/static/js/spec/student_account/account_settings_view_spec.js b/lms/static/js/spec/student_account/account_settings_view_spec.js
index 2d21870a03..638fd119f0 100644
--- a/lms/static/js/spec/student_account/account_settings_view_spec.js
+++ b/lms/static/js/spec/student_account/account_settings_view_spec.js
@@ -8,45 +8,43 @@ define(['backbone',
'js/student_account/models/user_account_model',
'js/student_account/views/account_settings_view'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, FieldViews, UserAccountModel,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, FieldViews, UserAccountModel,
AccountSettingsView) {
'use strict';
- describe("edx.user.AccountSettingsView", function () {
-
- var createAccountSettingsView = function () {
-
+ describe('edx.user.AccountSettingsView', function() {
+ var createAccountSettingsView = function() {
var model = new UserAccountModel();
model.set(Helpers.createAccountSettingsData());
var aboutSectionsData = [
{
- title: "Basic Account Information",
+ title: 'Basic Account Information',
fields: [
{
view: new FieldViews.ReadonlyFieldView({
model: model,
- title: "Username",
- valueAttribute: "username"
+ title: 'Username',
+ valueAttribute: 'username'
})
},
{
view: new FieldViews.TextFieldView({
model: model,
- title: "Full Name",
- valueAttribute: "name"
+ title: 'Full Name',
+ valueAttribute: 'name'
})
}
]
},
{
- title: "Additional Information",
+ title: 'Additional Information',
fields: [
{
view: new FieldViews.DropdownFieldView({
model: model,
- title: "Education Completed",
- valueAttribute: "level_of_education",
+ title: 'Education Completed',
+ valueAttribute: 'level_of_education',
options: Helpers.FIELD_OPTIONS
})
}
@@ -65,12 +63,11 @@ define(['backbone',
return accountSettingsView;
};
- beforeEach(function () {
+ beforeEach(function() {
setFixtures('
');
});
- it("shows loading error correctly", function() {
-
+ it('shows loading error correctly', function() {
var accountSettingsView = createAccountSettingsView();
accountSettingsView.render();
@@ -84,8 +81,7 @@ define(['backbone',
Helpers.expectSettingsSectionsButNotFieldsToBeRendered(accountSettingsView);
});
- it("renders all fields as expected", function() {
-
+ it('renders all fields as expected', function() {
var accountSettingsView = createAccountSettingsView();
accountSettingsView.render();
@@ -98,6 +94,5 @@ define(['backbone',
Helpers.expectLoadingErrorIsVisible(accountSettingsView, false);
Helpers.expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView);
});
-
});
});
diff --git a/lms/static/js/spec/student_account/account_spec.js b/lms/static/js/spec/student_account/account_spec.js
index bbca8f8ee2..e7504499ba 100644
--- a/lms/static/js/spec/student_account/account_spec.js
+++ b/lms/static/js/spec/student_account/account_spec.js
@@ -1,6 +1,6 @@
define(['js/student_account/account'],
function() {
- describe("edx.student.account.AccountModel", function() {
+ describe('edx.student.account.AccountModel', function() {
'use strict';
var account = null;
@@ -18,73 +18,73 @@ define(['js/student_account/account'],
var EXPECTED_ERRORS = {
email: {
- email: "Please enter a valid email address"
+ email: 'Please enter a valid email address'
},
password: {
- password: "Please enter a valid password"
+ password: 'Please enter a valid password'
}
};
beforeEach(function() {
account = new edx.student.account.AccountModel();
account.set({
- email: "bob@example.com",
- password: "password"
+ email: 'bob@example.com',
+ password: 'password'
});
});
- it("accepts valid email addresses", function() {
- assertValid({email: "bob@example.com"}, true);
- assertValid({email: "bob+smith@example.com"}, true);
- assertValid({email: "bob+smith@example.com"}, true);
- assertValid({email: "bob+smith@example.com"}, true);
- assertValid({email: "bob@test.example.com"}, true);
- assertValid({email: "bob@test-example.com"}, true);
+ it('accepts valid email addresses', function() {
+ assertValid({email: 'bob@example.com'}, true);
+ assertValid({email: 'bob+smith@example.com'}, true);
+ assertValid({email: 'bob+smith@example.com'}, true);
+ assertValid({email: 'bob+smith@example.com'}, true);
+ assertValid({email: 'bob@test.example.com'}, true);
+ assertValid({email: 'bob@test-example.com'}, true);
});
- it("rejects blank email addresses", function() {
- assertValid({email: ""}, false, EXPECTED_ERRORS.email);
- assertValid({email: " "}, false, EXPECTED_ERRORS.email);
+ it('rejects blank email addresses', function() {
+ assertValid({email: ''}, false, EXPECTED_ERRORS.email);
+ assertValid({email: ' '}, false, EXPECTED_ERRORS.email);
});
- it("rejects invalid email addresses", function() {
- assertValid({email: "bob"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "bob@example"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "@"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "@example.com"}, false, EXPECTED_ERRORS.email);
+ it('rejects invalid email addresses', function() {
+ assertValid({email: 'bob'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: 'bob@example'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: '@'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: '@example.com'}, false, EXPECTED_ERRORS.email);
// The server will reject emails with non-ASCII unicode
// Technically these are valid email addresses, but the email validator
// in Django 1.4 will reject them anyway, so we should too.
- assertValid({email: "fŕáńḱ@example.com"}, false, EXPECTED_ERRORS.email);
- assertValid({email: "frank@éxáḿṕĺé.com"}, false, EXPECTED_ERRORS.email);
+ assertValid({email: 'fŕáńḱ@example.com'}, false, EXPECTED_ERRORS.email);
+ assertValid({email: 'frank@éxáḿṕĺé.com'}, false, EXPECTED_ERRORS.email);
});
- it("rejects a long email address", function() {
+ it('rejects a long email address', function() {
// Construct an email exactly one character longer than the maximum length
- var longEmail = new Array(account.EMAIL_MAX_LENGTH - 10).join("e") + "@example.com";
+ var longEmail = new Array(account.EMAIL_MAX_LENGTH - 10).join('e') + '@example.com';
assertValid({email: longEmail}, false, EXPECTED_ERRORS.email);
});
- it("accepts a valid password", function() {
- assertValid({password: "password-test123"}, true, EXPECTED_ERRORS.password);
+ it('accepts a valid password', function() {
+ assertValid({password: 'password-test123'}, true, EXPECTED_ERRORS.password);
});
- it("rejects a short password", function() {
- assertValid({password: ""}, false, EXPECTED_ERRORS.password);
- assertValid({password: "a"}, false, EXPECTED_ERRORS.password);
- assertValid({password: "aa"}, true, EXPECTED_ERRORS.password);
+ it('rejects a short password', function() {
+ assertValid({password: ''}, false, EXPECTED_ERRORS.password);
+ assertValid({password: 'a'}, false, EXPECTED_ERRORS.password);
+ assertValid({password: 'aa'}, true, EXPECTED_ERRORS.password);
});
- it("rejects a long password", function() {
+ it('rejects a long password', function() {
// Construct a password exactly one character longer than the maximum length
- var longPassword = new Array(account.PASSWORD_MAX_LENGTH + 2).join("a");
+ var longPassword = new Array(account.PASSWORD_MAX_LENGTH + 2).join('a');
assertValid({password: longPassword}, false, EXPECTED_ERRORS.password);
});
});
- describe("edx.student.account.AccountView", function() {
+ describe('edx.student.account.AccountView', function() {
var view = null,
ajaxSuccess = true;
@@ -108,7 +108,7 @@ define(['js/student_account/account'],
expect(ajaxArgs.url).toEqual(url);
expect(ajaxArgs.type).toEqual(method);
expect(ajaxArgs.data).toEqual(data);
- expect(ajaxArgs.headers.hasOwnProperty("X-CSRFToken")).toBe(true);
+ expect(ajaxArgs.headers.hasOwnProperty('X-CSRFToken')).toBe(true);
};
var assertStatus = function(selection, success, errorClass, expectedStatus) {
@@ -121,13 +121,13 @@ define(['js/student_account/account'],
};
beforeEach(function() {
- var fixture = readFixtures("templates/student_account/account.underscore");
- setFixtures("
" + fixture + "
");
+ var fixture = readFixtures('templates/student_account/account.underscore');
+ setFixtures('
' + fixture + '
');
view = new edx.student.account.AccountView().render();
// Stub Ajax calls to return success/failure
- spyOn($, "ajax").and.callFake(function() {
+ spyOn($, 'ajax').and.callFake(function() {
return $.Deferred(function(defer) {
if (ajaxSuccess) {
defer.resolve();
@@ -138,63 +138,63 @@ define(['js/student_account/account'],
});
});
- it("requests an email address change", function() {
- requestEmailChange("bob@example.com", "password");
- assertAjax("email", "POST", {
- email: "bob@example.com",
- password: "password"
+ it('requests an email address change', function() {
+ requestEmailChange('bob@example.com', 'password');
+ assertAjax('email', 'POST', {
+ email: 'bob@example.com',
+ password: 'password'
});
- assertStatus(view.$requestStatus, true, "error", "Please check your email to confirm the change");
+ assertStatus(view.$requestStatus, true, 'error', 'Please check your email to confirm the change');
});
- it("displays email validation errors", function() {
+ it('displays email validation errors', function() {
// Invalid email should display an error
- requestEmailChange("invalid", "password");
- assertStatus(view.$emailStatus, false, "validation-error", "Please enter a valid email address");
+ requestEmailChange('invalid', 'password');
+ assertStatus(view.$emailStatus, false, 'validation-error', 'Please enter a valid email address');
// Once the error is fixed, the status should return to normal
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$emailStatus, true, "validation-error", "");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$emailStatus, true, 'validation-error', '');
});
- it("displays an invalid password error", function() {
+ it('displays an invalid password error', function() {
// Password cannot be empty
- requestEmailChange("bob@example.com", "");
- assertStatus(view.$passwordStatus, false, "validation-error", "Please enter a valid password");
+ requestEmailChange('bob@example.com', '');
+ assertStatus(view.$passwordStatus, false, 'validation-error', 'Please enter a valid password');
// Once the error is fixed, the status should return to normal
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$passwordStatus, true, "validation-error", "");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$passwordStatus, true, 'validation-error', '');
});
- it("displays server errors", function() {
+ it('displays server errors', function() {
// Simulate an error from the server
ajaxSuccess = false;
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$requestStatus, false, "error", "The data could not be saved.");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$requestStatus, false, 'error', 'The data could not be saved.');
// On retry, it should succeed
ajaxSuccess = true;
- requestEmailChange("bob@example.com", "password");
- assertStatus(view.$requestStatus, true, "error", "Please check your email to confirm the change");
+ requestEmailChange('bob@example.com', 'password');
+ assertStatus(view.$requestStatus, true, 'error', 'Please check your email to confirm the change');
});
- it("requests a password reset", function() {
+ it('requests a password reset', function() {
requestPasswordChange();
- assertAjax("password", "POST", {});
- assertStatus(view.$passwordResetStatus, true, "error", "Password reset email sent. Follow the link in the email to change your password.");
+ assertAjax('password', 'POST', {});
+ assertStatus(view.$passwordResetStatus, true, 'error', 'Password reset email sent. Follow the link in the email to change your password.');
});
- it("displays an error message if a password reset email could not be sent", function() {
+ it('displays an error message if a password reset email could not be sent', function() {
// Simulate an error from the server
ajaxSuccess = false;
requestPasswordChange();
- assertStatus(view.$passwordResetStatus, false, "error", "We weren't able to send you a password reset email.");
+ assertStatus(view.$passwordResetStatus, false, 'error', "We weren't able to send you a password reset email.");
// Retry, this time simulating success
ajaxSuccess = true;
requestPasswordChange();
- assertStatus(view.$passwordResetStatus, true, "error", "Password reset email sent. Follow the link in the email to change your password.");
+ assertStatus(view.$passwordResetStatus, true, 'error', 'Password reset email sent. Follow the link in the email to change your password.');
});
});
}
diff --git a/lms/static/js/spec/student_account/emailoptin_spec.js b/lms/static/js/spec/student_account/emailoptin_spec.js
index 00b49b4efa..6ef8b247e4 100644
--- a/lms/static/js/spec/student_account/emailoptin_spec.js
+++ b/lms/static/js/spec/student_account/emailoptin_spec.js
@@ -1,19 +1,18 @@
define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account/emailoptin'],
- function( AjaxHelpers, EmailOptInInterface ) {
+ function(AjaxHelpers, EmailOptInInterface) {
'use strict';
- describe( 'EmailOptInInterface', function() {
-
+ describe('EmailOptInInterface', function() {
var COURSE_KEY = 'edX/DemoX/Fall',
EMAIL_OPT_IN = 'True',
EMAIL_OPT_IN_URL = '/user_api/v1/preferences/email_opt_in/';
it('Opts in for organization emails', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EmailOptInInterface.setPreference( COURSE_KEY, EMAIL_OPT_IN );
+ EmailOptInInterface.setPreference(COURSE_KEY, EMAIL_OPT_IN);
// Expect that the correct request was made to the server
AjaxHelpers.expectRequest(
diff --git a/lms/static/js/spec/student_account/enrollment_spec.js b/lms/static/js/spec/student_account/enrollment_spec.js
index d7dea0512f..06c758fbf3 100644
--- a/lms/static/js/spec/student_account/enrollment_spec.js
+++ b/lms/static/js/spec/student_account/enrollment_spec.js
@@ -1,9 +1,8 @@
define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account/enrollment'],
- function( AjaxHelpers, EnrollmentInterface ) {
+ function(AjaxHelpers, EnrollmentInterface) {
'use strict';
- describe( 'EnrollmentInterface', function() {
-
+ describe('EnrollmentInterface', function() {
var COURSE_KEY = 'edX/DemoX/Fall',
ENROLL_URL = '/api/commerce/v0/baskets/',
FORWARD_URL = '/course_modes/choose/edX/DemoX/Fall/',
@@ -16,10 +15,10 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
it('enrolls a user in a course', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EnrollmentInterface.enroll( COURSE_KEY, FORWARD_URL );
+ EnrollmentInterface.enroll(COURSE_KEY, FORWARD_URL);
// Expect that the correct request was made to the server
AjaxHelpers.expectRequest(
@@ -33,29 +32,29 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
AjaxHelpers.respondWithJson(requests, {});
// Verify that the user was redirected correctly
- expect( EnrollmentInterface.redirect ).toHaveBeenCalledWith( FORWARD_URL );
+ expect(EnrollmentInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
it('redirects the user if enrollment fails', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EnrollmentInterface.enroll( COURSE_KEY, FORWARD_URL );
+ EnrollmentInterface.enroll(COURSE_KEY, FORWARD_URL);
// Simulate an error response from the server
AjaxHelpers.respondWithError(requests);
// Verify that the user was still redirected
- expect(EnrollmentInterface.redirect).toHaveBeenCalledWith( FORWARD_URL );
+ expect(EnrollmentInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
it('redirects the user if blocked by an embargo', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to enroll the user
- EnrollmentInterface.enroll( COURSE_KEY, FORWARD_URL );
+ EnrollmentInterface.enroll(COURSE_KEY, FORWARD_URL);
// Simulate an error response (403) from the server
// with a "user_message_url" parameter for the redirect.
@@ -63,14 +62,12 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
// explaining why he/she can't enroll.
AjaxHelpers.respondWithError(
requests, 403,
- { 'user_message_url': EMBARGO_MSG_URL }
+ {'user_message_url': EMBARGO_MSG_URL}
);
// Verify that the user was redirected
- expect(EnrollmentInterface.redirect).toHaveBeenCalledWith( EMBARGO_MSG_URL );
-
+ expect(EnrollmentInterface.redirect).toHaveBeenCalledWith(EMBARGO_MSG_URL);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_account/finish_auth_spec.js b/lms/static/js/spec/student_account/finish_auth_spec.js
index fcc53a0d59..89e7bc5368 100644
--- a/lms/static/js/spec/student_account/finish_auth_spec.js
+++ b/lms/static/js/spec/student_account/finish_auth_spec.js
@@ -1,42 +1,41 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'jquery.url',
- 'utility',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/views/FinishAuthView',
- 'js/student_account/enrollment',
- 'js/student_account/shoppingcart',
- 'js/student_account/emailoptin'
- ],
+ 'jquery',
+ 'jquery.url',
+ 'utility',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/views/FinishAuthView',
+ 'js/student_account/enrollment',
+ 'js/student_account/shoppingcart',
+ 'js/student_account/emailoptin'
+ ],
function($, url, utility, AjaxHelpers, FinishAuthView, EnrollmentInterface, ShoppingCartInterface,
EmailOptInInterface) {
+ describe('FinishAuthView', function() {
+ var requests = null,
+ view = null,
+ FORWARD_URL = '/courseware/next',
+ COURSE_KEY = 'course-v1:edX+test+15';
- describe('FinishAuthView', function() {
- var requests = null,
- view = null,
- FORWARD_URL = '/courseware/next',
- COURSE_KEY = 'course-v1:edX+test+15';
-
- var ajaxSpyAndInitialize = function(that) {
+ var ajaxSpyAndInitialize = function(that) {
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
+ requests = AjaxHelpers.requests(that);
// Initialize the access view
- view = new FinishAuthView({});
+ view = new FinishAuthView({});
// Mock the redirect call
- spyOn( view, 'redirect' ).and.callFake( function() {} );
+ spyOn(view, 'redirect').and.callFake(function() {});
// Mock the enrollment and shopping cart interfaces
- spyOn( EnrollmentInterface, 'enroll' ).and.callFake( function() {} );
- spyOn( ShoppingCartInterface, 'addCourseToCart' ).and.callFake( function() {} );
- spyOn( EmailOptInInterface, 'setPreference' )
- .and.callFake( function() { return {'always': function(r) { r(); }}; } );
+ spyOn(EnrollmentInterface, 'enroll').and.callFake(function() {});
+ spyOn(ShoppingCartInterface, 'addCourseToCart').and.callFake(function() {});
+ spyOn(EmailOptInInterface, 'setPreference')
+ .and.callFake(function() { return {'always': function(r) { r(); }}; });
- view.render();
- };
+ view.render();
+ };
/**
* Simulate query string params.
@@ -44,173 +43,173 @@
* @param {object} params Parameters to set, each of which
* should be prefixed with '?'
*/
- var setFakeQueryParams = function( params ) {
- spyOn( $, 'url' ).and.callFake(function( requestedParam ) {
- if ( params.hasOwnProperty(requestedParam) ) {
- return params[requestedParam];
- }
- });
- };
+ var setFakeQueryParams = function(params) {
+ spyOn($, 'url').and.callFake(function(requestedParam) {
+ if (params.hasOwnProperty(requestedParam)) {
+ return params[requestedParam];
+ }
+ });
+ };
- beforeEach(function() {
+ beforeEach(function() {
// Stub analytics tracking
- window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
- });
-
- it('saves the email opt-in preference before enrollment', function() {
- // Simulate providing enrollment query string params
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?email_opt_in': 'true'
+ window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'pageview', 'trackLink']);
});
- ajaxSpyAndInitialize(this);
+ it('saves the email opt-in preference before enrollment', function() {
+ // Simulate providing enrollment query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?email_opt_in': 'true'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to save the email opt in preference
- expect( EmailOptInInterface.setPreference ).toHaveBeenCalledWith(
+ expect(EmailOptInInterface.setPreference).toHaveBeenCalledWith(
COURSE_KEY,
'true'
);
// Expect that the view tried to enroll the student
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/course_modes/choose/' + COURSE_KEY + '/'
);
- });
-
- it('enrolls the user on auth complete', function() {
- // Simulate providing enrollment query string params
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY
});
- ajaxSpyAndInitialize(this);
+ it('enrolls the user on auth complete', function() {
+ // Simulate providing enrollment query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to enroll the student
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/course_modes/choose/' + COURSE_KEY + '/'
);
- });
-
- it('sends the user to the course mode selection flow with bulk purchase workflow', function() {
- // Simulate providing enrollment query string params
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?purchase_workflow': 'bulk'
});
- ajaxSpyAndInitialize(this);
+ it('sends the user to the course mode selection flow with bulk purchase workflow', function() {
+ // Simulate providing enrollment query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?purchase_workflow': 'bulk'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view redirected to the course
// mode select flow with the purchase_workflow parameter
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/course_modes/choose/' + COURSE_KEY + '/?purchase_workflow=bulk'
);
- });
-
- it('sends the user to the payment flow for a paid course mode', function() {
- // Simulate providing enrollment query string params
- // AND specifying a course mode.
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?course_mode': 'verified'
});
- ajaxSpyAndInitialize(this);
+ it('sends the user to the payment flow for a paid course mode', function() {
+ // Simulate providing enrollment query string params
+ // AND specifying a course mode.
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?course_mode': 'verified'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to auto-enroll the student
// with a redirect into the payment flow.
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/verify_student/start-flow/' + COURSE_KEY + '/'
);
- });
+ });
- it('sends the user to the payment flow for a paid course mode with bulk purchase workflow', function() {
+ it('sends the user to the payment flow for a paid course mode with bulk purchase workflow', function() {
// Simulate providing enrollment query string params
// AND specifying a course mode
// AND purchase workflow type.
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?course_mode': 'professional-no-id',
- '?purchase_workflow': 'bulk'
- });
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?course_mode': 'professional-no-id',
+ '?purchase_workflow': 'bulk'
+ });
- ajaxSpyAndInitialize(this);
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to auto-enroll the student
// with a redirect into the payment flow including the
// purchase_workflow parameter.
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(
COURSE_KEY,
'/verify_student/start-flow/' + COURSE_KEY + '/?purchase_workflow=bulk'
);
- });
-
- it('sends the user to the student dashboard for an unpaid course mode', function() {
- // Simulate providing enrollment query string params
- // AND specifying a course mode.
- setFakeQueryParams({
- '?enrollment_action': 'enroll',
- '?course_id': COURSE_KEY,
- '?course_mode': 'audit'
});
- ajaxSpyAndInitialize(this);
+ it('sends the user to the student dashboard for an unpaid course mode', function() {
+ // Simulate providing enrollment query string params
+ // AND specifying a course mode.
+ setFakeQueryParams({
+ '?enrollment_action': 'enroll',
+ '?course_id': COURSE_KEY,
+ '?course_mode': 'audit'
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried auto-enrolled the student
// and sent the student to the dashboard
// (skipping the payment flow).
- expect( EnrollmentInterface.enroll ).toHaveBeenCalledWith(COURSE_KEY, '/dashboard');
- });
-
- it('adds a white-label course to the shopping cart on auth complete', function() {
- // Simulate providing "add to cart" query string params
- setFakeQueryParams({
- '?enrollment_action': 'add_to_cart',
- '?course_id': COURSE_KEY
+ expect(EnrollmentInterface.enroll).toHaveBeenCalledWith(COURSE_KEY, '/dashboard');
});
- ajaxSpyAndInitialize(this);
+ it('adds a white-label course to the shopping cart on auth complete', function() {
+ // Simulate providing "add to cart" query string params
+ setFakeQueryParams({
+ '?enrollment_action': 'add_to_cart',
+ '?course_id': COURSE_KEY
+ });
+
+ ajaxSpyAndInitialize(this);
// Expect that the view tried to add the course to the user's shopping cart
- expect( ShoppingCartInterface.addCourseToCart ).toHaveBeenCalledWith( COURSE_KEY );
- });
+ expect(ShoppingCartInterface.addCourseToCart).toHaveBeenCalledWith(COURSE_KEY);
+ });
- it('redirects the user to the dashboard if no course is provided', function() {
- ajaxSpyAndInitialize(this);
+ it('redirects the user to the dashboard if no course is provided', function() {
+ ajaxSpyAndInitialize(this);
// Since we did not provide a ?next query param, expect a redirect to the dashboard.
- expect( view.redirect ).toHaveBeenCalledWith( '/dashboard' );
- });
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
- it('redirects the user to the next page when done', function() {
+ it('redirects the user to the next page when done', function() {
// Simulate providing a ?next query string parameter
- setFakeQueryParams({ '?next': FORWARD_URL });
+ setFakeQueryParams({'?next': FORWARD_URL});
- ajaxSpyAndInitialize(this);
+ ajaxSpyAndInitialize(this);
// Verify that we were redirected
- expect( view.redirect ).toHaveBeenCalledWith( FORWARD_URL );
- });
+ expect(view.redirect).toHaveBeenCalledWith(FORWARD_URL);
+ });
- it('ignores redirect to external URLs', function() {
+ it('ignores redirect to external URLs', function() {
// Simulate providing a ?next query string parameter
// that goes to an external URL
- setFakeQueryParams({ '?next': "http://www.example.com" });
+ setFakeQueryParams({'?next': 'http://www.example.com'});
- ajaxSpyAndInitialize(this);
+ ajaxSpyAndInitialize(this);
// Expect that we ignore the external URL and redirect to the dashboard
- expect( view.redirect ).toHaveBeenCalledWith( "/dashboard" );
+ expect(view.redirect).toHaveBeenCalledWith('/dashboard');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/helpers.js b/lms/static/js/spec/student_account/helpers.js
index 7cf34f8472..49e9bd44fa 100644
--- a/lms/static/js/spec/student_account/helpers.js
+++ b/lms/static/js/spec/student_account/helpers.js
@@ -23,7 +23,7 @@ define(['underscore'], function(_) {
requires_parental_consent: false,
country: '1',
language: null,
- bio: "About the student",
+ bio: 'About the student',
language_proficiencies: [{code: '1'}],
profile_image: PROFILE_IMAGE,
accomplishments_shared: false
@@ -52,7 +52,7 @@ define(['underscore'], function(_) {
var IMAGE_MAX_BYTES = 1024 * 1024;
var IMAGE_MIN_BYTES = 100;
- var expectLoadingIndicatorIsVisible = function (view, visible) {
+ var expectLoadingIndicatorIsVisible = function(view, visible) {
if (visible) {
expect($('.ui-loading-indicator')).not.toHaveClass('is-hidden');
} else {
@@ -60,7 +60,7 @@ define(['underscore'], function(_) {
}
};
- var expectLoadingErrorIsVisible = function (view, visible) {
+ var expectLoadingErrorIsVisible = function(view, visible) {
if (visible) {
expect(view.$('.ui-loading-error')).not.toHaveClass('is-hidden');
} else {
@@ -83,11 +83,11 @@ define(['underscore'], function(_) {
}
};
- var expectSettingsSectionsButNotFieldsToBeRendered = function (accountSettingsView) {
- expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView, false)
+ var expectSettingsSectionsButNotFieldsToBeRendered = function(accountSettingsView) {
+ expectSettingsSectionsAndFieldsToBeRendered(accountSettingsView, false);
};
- var expectSettingsSectionsAndFieldsToBeRendered = function (accountSettingsView, fieldsAreRendered) {
+ var expectSettingsSectionsAndFieldsToBeRendered = function(accountSettingsView, fieldsAreRendered) {
var sectionsData = accountSettingsView.options.tabSections.aboutTabSections;
var sectionElements = accountSettingsView.$('.section');
@@ -103,7 +103,7 @@ define(['underscore'], function(_) {
} else {
expect(sectionFieldElements.length).toBe(sectionsData[sectionIndex].fields.length);
- _.each(sectionFieldElements, function (sectionFieldElement, fieldIndex) {
+ _.each(sectionFieldElements, function(sectionFieldElement, fieldIndex) {
expectElementContainsField(sectionFieldElement, sectionsData[sectionIndex].fields[fieldIndex]);
});
}
@@ -127,6 +127,6 @@ define(['underscore'], function(_) {
expectLoadingErrorIsVisible: expectLoadingErrorIsVisible,
expectElementContainsField: expectElementContainsField,
expectSettingsSectionsButNotFieldsToBeRendered: expectSettingsSectionsButNotFieldsToBeRendered,
- expectSettingsSectionsAndFieldsToBeRendered: expectSettingsSectionsAndFieldsToBeRendered,
+ expectSettingsSectionsAndFieldsToBeRendered: expectSettingsSectionsAndFieldsToBeRendered
};
});
diff --git a/lms/static/js/spec/student_account/hinted_login_spec.js b/lms/static/js/spec/student_account/hinted_login_spec.js
index 80f6bfd585..5fd0ecaf96 100644
--- a/lms/static/js/spec/student_account/hinted_login_spec.js
+++ b/lms/static/js/spec/student_account/hinted_login_spec.js
@@ -1,90 +1,89 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/views/HintedLoginView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/views/HintedLoginView'
+ ],
function($, _, TemplateHelpers, AjaxHelpers, HintedLoginView) {
+ describe('edx.student.account.HintedLoginView', function() {
+ var view = null,
+ requests = null,
+ PLATFORM_NAME = 'edX',
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ],
+ secondaryProviders: [
+ {
+ id: 'saml-harvard',
+ name: 'Harvard',
+ iconClass: 'fa-university',
+ loginUrl: '/auth/login/tpa-saml/?auth_entry=account_login&idp=harvard',
+ registerUrl: '/auth/login/tpa-saml/?auth_entry=account_register&idp=harvard'
+ }
+ ]
+ };
- describe('edx.student.account.HintedLoginView', function() {
- var view = null,
- requests = null,
- PLATFORM_NAME = 'edX',
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ],
- secondaryProviders: [
- {
- id: 'saml-harvard',
- name: 'Harvard',
- iconClass: 'fa-university',
- loginUrl: '/auth/login/tpa-saml/?auth_entry=account_login&idp=harvard',
- registerUrl: '/auth/login/tpa-saml/?auth_entry=account_register&idp=harvard'
- }
- ]
- };
-
- var createHintedLoginView = function(hintedProvider) {
+ var createHintedLoginView = function(hintedProvider) {
// Initialize the login view
- view = new HintedLoginView({
- thirdPartyAuth: THIRD_PARTY_AUTH,
- hintedProvider: hintedProvider,
- platformName: PLATFORM_NAME
- });
+ view = new HintedLoginView({
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ hintedProvider: hintedProvider,
+ platformName: PLATFORM_NAME
+ });
// Mock the redirect call
- spyOn( view, 'redirect' ).and.callFake( function() {} );
+ spyOn(view, 'redirect').and.callFake(function() {});
- view.render();
- };
+ view.render();
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/hinted_login');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/hinted_login');
+ });
- it('displays a choice as two buttons', function() {
- createHintedLoginView("oa2-google-oauth2");
+ it('displays a choice as two buttons', function() {
+ createHintedLoginView('oa2-google-oauth2');
- expect($('.proceed-button.button-oa2-google-oauth2')).toBeVisible();
- expect($('.form-toggle')).toBeVisible();
- expect($('.proceed-button.button-oa2-facebook')).not.toBeVisible();
- });
+ expect($('.proceed-button.button-oa2-google-oauth2')).toBeVisible();
+ expect($('.form-toggle')).toBeVisible();
+ expect($('.proceed-button.button-oa2-facebook')).not.toBeVisible();
+ });
- it('works with secondary providers as well', function() {
- createHintedLoginView("saml-harvard");
+ it('works with secondary providers as well', function() {
+ createHintedLoginView('saml-harvard');
- expect($('.proceed-button.button-saml-harvard')).toBeVisible();
- expect($('.form-toggle')).toBeVisible();
- expect($('.proceed-button.button-oa2-google-oauth2')).not.toBeVisible();
- });
+ expect($('.proceed-button.button-saml-harvard')).toBeVisible();
+ expect($('.form-toggle')).toBeVisible();
+ expect($('.proceed-button.button-oa2-google-oauth2')).not.toBeVisible();
+ });
- it('redirects the user to the hinted provider if the user clicks the proceed button', function() {
- createHintedLoginView('oa2-google-oauth2');
+ it('redirects the user to the hinted provider if the user clicks the proceed button', function() {
+ createHintedLoginView('oa2-google-oauth2');
// Click the "Yes, proceed" button
- $('.proceed-button').click();
+ $('.proceed-button').click();
- expect(view.redirect).toHaveBeenCalledWith( '/auth/login/google-oauth2/?auth_entry=account_login' );
+ expect(view.redirect).toHaveBeenCalledWith('/auth/login/google-oauth2/?auth_entry=account_login');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/institution_login_spec.js b/lms/static/js/spec/student_account/institution_login_spec.js
index d087509ecc..839eefb25b 100644
--- a/lms/static/js/spec/student_account/institution_login_spec.js
+++ b/lms/static/js/spec/student_account/institution_login_spec.js
@@ -1,87 +1,85 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'js/student_account/views/InstitutionLoginView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/student_account/views/InstitutionLoginView'
+ ],
function($, _, TemplateHelpers, InstitutionLoginView) {
+ describe('edx.student.account.InstitutionLoginView', function() {
+ var view = null,
+ PLATFORM_NAME = 'edX',
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [],
+ secondaryProviders: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ]
+ };
- describe('edx.student.account.InstitutionLoginView', function() {
- var view = null,
- PLATFORM_NAME = 'edX',
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [],
- secondaryProviders: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ]
+ var createInstLoginView = function(mode) {
+ // Initialize the login view
+ view = new InstitutionLoginView({
+ mode: mode,
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ platformName: PLATFORM_NAME
+ });
+ view.render();
};
- var createInstLoginView = function(mode) {
- // Initialize the login view
- view = new InstitutionLoginView({
- mode: mode,
- thirdPartyAuth: THIRD_PARTY_AUTH,
- platformName: PLATFORM_NAME
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/institution_login');
+ TemplateHelpers.installTemplate('templates/student_account/institution_register');
});
- view.render();
- };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/institution_login');
- TemplateHelpers.installTemplate('templates/student_account/institution_register');
- });
+ it('displays a list of providers', function() {
+ var $google, $facebook;
- it('displays a list of providers', function() {
- var $google, $facebook;
-
- createInstLoginView('login');
- expect($('#institution_login-form').html()).not.toBe("");
- $google = $('li a:contains("Google")');
- expect($google).toBeVisible();
- expect($google).toHaveAttr(
+ createInstLoginView('login');
+ expect($('#institution_login-form').html()).not.toBe('');
+ $google = $('li a:contains("Google")');
+ expect($google).toBeVisible();
+ expect($google).toHaveAttr(
'href', '/auth/login/google-oauth2/?auth_entry=account_login'
);
- $facebook = $('li a:contains("Facebook")');
- expect($facebook).toBeVisible();
- expect($facebook).toHaveAttr(
+ $facebook = $('li a:contains("Facebook")');
+ expect($facebook).toBeVisible();
+ expect($facebook).toHaveAttr(
'href', '/auth/login/facebook/?auth_entry=account_login'
);
- });
+ });
- it('displays a list of providers', function() {
- var $google, $facebook;
+ it('displays a list of providers', function() {
+ var $google, $facebook;
- createInstLoginView('register');
- expect($('#institution_login-form').html()).not.toBe("");
- $google = $('li a:contains("Google")');
- expect($google).toBeVisible();
- expect($google).toHaveAttr(
+ createInstLoginView('register');
+ expect($('#institution_login-form').html()).not.toBe('');
+ $google = $('li a:contains("Google")');
+ expect($google).toBeVisible();
+ expect($google).toHaveAttr(
'href', '/auth/login/google-oauth2/?auth_entry=account_register'
);
- $facebook = $('li a:contains("Facebook")');
- expect($facebook).toBeVisible();
- expect($facebook).toHaveAttr(
+ $facebook = $('li a:contains("Facebook")');
+ expect($facebook).toBeVisible();
+ expect($facebook).toHaveAttr(
'href', '/auth/login/facebook/?auth_entry=account_register'
);
+ });
});
-
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/login_spec.js b/lms/static/js/spec/student_account/login_spec.js
index 2817b965db..7ecc50ee7b 100644
--- a/lms/static/js/spec/student_account/login_spec.js
+++ b/lms/static/js/spec/student_account/login_spec.js
@@ -1,321 +1,320 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'sinon',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/models/LoginModel',
- 'js/student_account/views/LoginView',
- 'js/student_account/models/PasswordResetModel'
- ],
+ 'jquery',
+ 'underscore',
+ 'sinon',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/models/LoginModel',
+ 'js/student_account/views/LoginView',
+ 'js/student_account/models/PasswordResetModel'
+ ],
function($, _, sinon, TemplateHelpers, AjaxHelpers, LoginModel, LoginView, PasswordResetModel) {
+ describe('edx.student.account.LoginView', function() {
+ var model = null,
+ resetModel = null,
+ view = null,
+ requests = null,
+ authComplete = false,
+ PLATFORM_NAME = 'edX',
+ USER_DATA = {
+ email: 'xsy@edx.org',
+ password: 'xsyisawesome',
+ remember: true
+ },
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ]
+ },
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/user_api/v1/account/login_session/',
+ fields: [
+ {
+ placeholder: 'username@domain.com',
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'email',
+ required: true,
+ instructions: 'Enter your email.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'password',
+ label: 'Password',
+ defaultValue: '',
+ type: 'password',
+ required: true,
+ instructions: 'Enter your password.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'remember',
+ label: 'Remember me',
+ defaultValue: '',
+ type: 'checkbox',
+ required: true,
+ instructions: 'Agree to the terms of service.',
+ restrictions: {}
+ }
+ ]
+ },
+ COURSE_ID = 'edX/demoX/Fall';
- describe('edx.student.account.LoginView', function() {
- var model = null,
- resetModel = null,
- view = null,
- requests = null,
- authComplete = false,
- PLATFORM_NAME = 'edX',
- USER_DATA = {
- email: 'xsy@edx.org',
- password: 'xsyisawesome',
- remember: true
- },
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ]
- },
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/user_api/v1/account/login_session/',
- fields: [
- {
- placeholder: 'username@domain.com',
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'email',
- required: true,
- instructions: 'Enter your email.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'password',
- label: 'Password',
- defaultValue: '',
- type: 'password',
- required: true,
- instructions: 'Enter your password.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'remember',
- label: 'Remember me',
- defaultValue: '',
- type: 'checkbox',
- required: true,
- instructions: 'Agree to the terms of service.',
- restrictions: {}
- }
- ]
- },
- COURSE_ID = 'edX/demoX/Fall';
-
- var createLoginView = function(test) {
+ var createLoginView = function(test) {
// Initialize the login model
- model = new LoginModel({}, {
- url: FORM_DESCRIPTION.submit_url,
- method: FORM_DESCRIPTION.method
- });
+ model = new LoginModel({}, {
+ url: FORM_DESCRIPTION.submit_url,
+ method: FORM_DESCRIPTION.method
+ });
// Initialize the passwordReset model
- resetModel = new PasswordResetModel({}, {
- method: 'GET',
- url: '#'
- });
+ resetModel = new PasswordResetModel({}, {
+ method: 'GET',
+ url: '#'
+ });
// Initialize the login view
- view = new LoginView({
- fields: FORM_DESCRIPTION.fields,
- model: model,
- resetModel: resetModel,
- thirdPartyAuth: THIRD_PARTY_AUTH,
- platformName: PLATFORM_NAME
- });
+ view = new LoginView({
+ fields: FORM_DESCRIPTION.fields,
+ model: model,
+ resetModel: resetModel,
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ platformName: PLATFORM_NAME
+ });
// Spy on AJAX requests
- requests = AjaxHelpers.requests(test);
+ requests = AjaxHelpers.requests(test);
// Intercept events from the view
- authComplete = false;
- view.on("auth-complete", function() {
- authComplete = true;
- });
- };
+ authComplete = false;
+ view.on('auth-complete', function() {
+ authComplete = true;
+ });
+ };
- var submitForm = function(validationSuccess) {
+ var submitForm = function(validationSuccess) {
// Create a fake click event
- var clickEvent = $.Event('click');
+ var clickEvent = $.Event('click');
// Simulate manual entry of login form data
- $('#login-email').val(USER_DATA.email);
- $('#login-password').val(USER_DATA.password);
+ $('#login-email').val(USER_DATA.email);
+ $('#login-password').val(USER_DATA.password);
// Check the 'Remember me' checkbox
- $('#login-remember').prop('checked', USER_DATA.remember);
+ $('#login-remember').prop('checked', USER_DATA.remember);
// If validationSuccess isn't passed, we avoid
// spying on `view.validate` twice
- if ( !_.isUndefined(validationSuccess) ) {
+ if (!_.isUndefined(validationSuccess)) {
// Force validation to return as expected
- spyOn(view, 'validate').and.returnValue({
- isValid: validationSuccess,
- message: 'Submission was validated.'
- });
- }
+ spyOn(view, 'validate').and.returnValue({
+ isValid: validationSuccess,
+ message: 'Submission was validated.'
+ });
+ }
// Submit the email address
- view.submitForm(clickEvent);
- };
+ view.submitForm(clickEvent);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/login');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/login');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ });
- it('logs the user in', function() {
- createLoginView(this);
+ it('logs the user in', function() {
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
+ expect(view.$submitButton).toHaveAttr('disabled');
// Verify that the client contacts the server with the expected data
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
$.param(USER_DATA)
);
// Respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Verify that auth-complete is triggered
- expect(authComplete).toBe(true);
- });
+ expect(authComplete).toBe(true);
+ });
- it('sends analytics info containing the enrolled course ID', function() {
- var expectedData;
+ it('sends analytics info containing the enrolled course ID', function() {
+ var expectedData;
- createLoginView(this);
+ createLoginView(this);
// Simulate that the user is attempting to enroll in a course
// by setting the course_id query string param.
- spyOn($, 'url').and.callFake(function( param ) {
- if (param === '?course_id') {
- return encodeURIComponent( COURSE_ID );
- }
- });
+ spyOn($, 'url').and.callFake(function(param) {
+ if (param === '?course_id') {
+ return encodeURIComponent(COURSE_ID);
+ }
+ });
// Attempt to login
- submitForm( true );
+ submitForm(true);
// Verify that the client sent the course ID for analytics
- expectedData = {};
- $.extend(expectedData, USER_DATA, {
- analytics: JSON.stringify({
- enroll_course_id: COURSE_ID
- })
- });
+ expectedData = {};
+ $.extend(expectedData, USER_DATA, {
+ analytics: JSON.stringify({
+ enroll_course_id: COURSE_ID
+ })
+ });
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param( expectedData )
+ $.param(expectedData)
);
- });
+ });
- it('displays third-party auth login buttons', function() {
- createLoginView(this);
+ it('displays third-party auth login buttons', function() {
+ createLoginView(this);
// Verify that Google and Facebook registration buttons are displayed
- expect($('.button-oa2-google-oauth2')).toBeVisible();
- expect($('.button-oa2-facebook')).toBeVisible();
- });
+ expect($('.button-oa2-google-oauth2')).toBeVisible();
+ expect($('.button-oa2-facebook')).toBeVisible();
+ });
- it('displays a link to the password reset form', function() {
- createLoginView(this);
+ it('displays a link to the password reset form', function() {
+ createLoginView(this);
// Verify that the password reset link is displayed
- expect($('.forgot-password')).toBeVisible();
- });
+ expect($('.forgot-password')).toBeVisible();
+ });
- it('validates login form fields', function() {
- createLoginView(this);
+ it('validates login form fields', function() {
+ createLoginView(this);
- submitForm(true);
+ submitForm(true);
// Verify that validation of form fields occurred
- expect(view.validate).toHaveBeenCalledWith($('#login-email')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#login-password')[0]);
- });
+ expect(view.validate).toHaveBeenCalledWith($('#login-email')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#login-password')[0]);
+ });
- it('displays login form validation errors', function() {
- createLoginView(this);
+ it('displays login form validation errors', function() {
+ createLoginView(this);
// Submit the form, with failed validation
- submitForm(false);
+ submitForm(false);
// Verify that submission errors are visible
- expect(view.$errors).not.toHaveClass('hidden');
+ expect(view.$errors).not.toHaveClass('hidden');
// Expect auth complete NOT to have been triggered
- expect(authComplete).toBe(false);
+ expect(authComplete).toBe(false);
// Form button should be re-enabled when errors occur
- expect(view.$submitButton).not.toHaveAttr('disabled');
- });
+ expect(view.$submitButton).not.toHaveAttr('disabled');
+ });
- it('displays an error if the server returns an error while logging in', function() {
- createLoginView(this);
+ it('displays an error if the server returns an error while logging in', function() {
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests);
+ AjaxHelpers.respondWithError(requests);
// Expect that an error is displayed and that auth complete is not triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
// Form button should be re-enabled on server failure.
- expect(view.$submitButton).not.toHaveAttr('disabled');
+ expect(view.$submitButton).not.toHaveAttr('disabled');
// If we try again and succeed, the error should go away
- submitForm();
+ submitForm();
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
+ expect(view.$submitButton).toHaveAttr('disabled');
// This time, respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the error is hidden and auth complete is triggered
- expect(view.$errors).toHaveClass('hidden');
- expect(authComplete).toBe(true);
- });
+ expect(view.$errors).toHaveClass('hidden');
+ expect(authComplete).toBe(true);
+ });
- it('displays an error if there is no internet connection', function () {
- var clock,
- oldTimeout,
- timeout;
+ it('displays an error if there is no internet connection', function() {
+ var clock,
+ oldTimeout,
+ timeout;
// We're defining "no internet connection" in this case as the
// request timing out. We use a combination of the sinon fake
// timer and jQuery.ajaxSetup() to force a request timeout.
- clock = sinon.useFakeTimers();
- oldTimeout = $.ajaxSetup().timeout;
- timeout = 1;
- $.ajaxSetup({timeout: timeout});
+ clock = sinon.useFakeTimers();
+ oldTimeout = $.ajaxSetup().timeout;
+ timeout = 1;
+ $.ajaxSetup({timeout: timeout});
- createLoginView(this);
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate a request timeout
- clock.tick(timeout + 1);
+ clock.tick(timeout + 1);
// Expect that an error is displayed and that auth complete is not triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
- expect(view.$errors.text()).toContain(
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
+ expect(view.$errors.text()).toContain(
'An error has occurred. Check your Internet connection and try again.'
);
// Finally, restore the old timeout and turn off the fake timer.
- $.ajaxSetup({timeout: oldTimeout});
- clock.restore();
- });
+ $.ajaxSetup({timeout: oldTimeout});
+ clock.restore();
+ });
- it('displays an error if there is a server error', function () {
- createLoginView(this);
+ it('displays an error if there is a server error', function() {
+ createLoginView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests, 500);
+ AjaxHelpers.respondWithError(requests, 500);
// Expect that an error is displayed and that auth complete is not triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
- expect(view.$errors.text()).toContain(
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
+ expect(view.$errors.text()).toContain(
'An error has occurred. Try refreshing the page, or check your Internet connection.'
);
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/logistration_factory_spec.js b/lms/static/js/spec/student_account/logistration_factory_spec.js
index d793360853..05c36b3a02 100644
--- a/lms/static/js/spec/student_account/logistration_factory_spec.js
+++ b/lms/static/js/spec/student_account/logistration_factory_spec.js
@@ -1,17 +1,16 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/logistration_factory'
- ],
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/logistration_factory'
+ ],
function($, _, Backbone, TemplateHelpers, AjaxHelpers, LogistrationFactory) {
-
- describe('Logistration Factory', function() {
- var FORM_DESCRIPTION = {
+ describe('Logistration Factory', function() {
+ var FORM_DESCRIPTION = {
method: 'post',
submit_url: '/submit',
fields: [
@@ -40,91 +39,91 @@
]
};
- var initializeLogistrationFactory = function(that, mode, nextUrl, finishAuthUrl) {
- var options = {
- initial_mode: mode,
- third_party_auth: {
- currentProvider: null,
- providers: [],
- secondaryProviders: [{name: 'provider'}],
- finishAuthUrl: finishAuthUrl
- },
- login_redirect_url: nextUrl, // undefined for default
- platform_name: 'edX',
- login_form_desc: FORM_DESCRIPTION,
- registration_form_desc: FORM_DESCRIPTION,
- password_reset_form_desc: FORM_DESCRIPTION
- };
+ var initializeLogistrationFactory = function(that, mode, nextUrl, finishAuthUrl) {
+ var options = {
+ initial_mode: mode,
+ third_party_auth: {
+ currentProvider: null,
+ providers: [],
+ secondaryProviders: [{name: 'provider'}],
+ finishAuthUrl: finishAuthUrl
+ },
+ login_redirect_url: nextUrl, // undefined for default
+ platform_name: 'edX',
+ login_form_desc: FORM_DESCRIPTION,
+ registration_form_desc: FORM_DESCRIPTION,
+ password_reset_form_desc: FORM_DESCRIPTION
+ };
// Initialize the logistration Factory
- LogistrationFactory(options);
- };
+ LogistrationFactory(options);
+ };
- var assertForms = function(visibleForm, hiddenFormsList) {
- expect($(visibleForm)).not.toHaveClass('hidden');
+ var assertForms = function(visibleForm, hiddenFormsList) {
+ expect($(visibleForm)).not.toHaveClass('hidden');
- _.each(hiddenFormsList, function (hiddenForm) {
- expect($(hiddenForm)).toHaveClass('hidden');
- }, this);
- };
+ _.each(hiddenFormsList, function(hiddenForm) {
+ expect($(hiddenForm)).toHaveClass('hidden');
+ }, this);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/access');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- TemplateHelpers.installTemplate('templates/student_account/login');
- TemplateHelpers.installTemplate('templates/student_account/register');
- TemplateHelpers.installTemplate('templates/student_account/password_reset')
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/access');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ TemplateHelpers.installTemplate('templates/student_account/login');
+ TemplateHelpers.installTemplate('templates/student_account/register');
+ TemplateHelpers.installTemplate('templates/student_account/password_reset');
+ });
- afterEach(function() {
- Backbone.history.stop();
- });
+ afterEach(function() {
+ Backbone.history.stop();
+ });
- it('can initially render the login form', function() {
- var hiddenFormsList;
+ it('can initially render the login form', function() {
+ var hiddenFormsList;
- initializeLogistrationFactory(this, 'login');
+ initializeLogistrationFactory(this, 'login');
/* Verify that only login form is expanded, and that the
/* all other logistration forms are collapsed.
*/
- hiddenFormsList = [
- '#register-form',
- '#password-reset-form'
- ];
- assertForms('#login-form', hiddenFormsList);
- });
+ hiddenFormsList = [
+ '#register-form',
+ '#password-reset-form'
+ ];
+ assertForms('#login-form', hiddenFormsList);
+ });
- it('can initially render the registration form', function() {
- var hiddenFormsList;
+ it('can initially render the registration form', function() {
+ var hiddenFormsList;
- initializeLogistrationFactory(this, 'register');
+ initializeLogistrationFactory(this, 'register');
/* Verify that only registration form is expanded, and that the
/* all other logistration forms are collapsed.
*/
- hiddenFormsList = [
- '#login-form',
- '#password-reset-form'
- ];
- assertForms('#register-form', hiddenFormsList);
- });
+ hiddenFormsList = [
+ '#login-form',
+ '#password-reset-form'
+ ];
+ assertForms('#register-form', hiddenFormsList);
+ });
- it('can initially render the password reset form', function() {
- var hiddenFormsList;
+ it('can initially render the password reset form', function() {
+ var hiddenFormsList;
- initializeLogistrationFactory(this, 'reset');
+ initializeLogistrationFactory(this, 'reset');
/* Verify that only password reset form is expanded, and that the
/* all other logistration forms are collapsed.
*/
- hiddenFormsList = [
- '#login-form',
- '#register-form'
- ];
- assertForms('#password-reset-form', hiddenFormsList);
+ hiddenFormsList = [
+ '#login-form',
+ '#register-form'
+ ];
+ assertForms('#password-reset-form', hiddenFormsList);
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/password_reset_spec.js b/lms/static/js/spec/student_account/password_reset_spec.js
index 43fd551e89..2124d6c57b 100644
--- a/lms/static/js/spec/student_account/password_reset_spec.js
+++ b/lms/static/js/spec/student_account/password_reset_spec.js
@@ -1,147 +1,146 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/models/PasswordResetModel',
- 'js/student_account/views/PasswordResetView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/models/PasswordResetModel',
+ 'js/student_account/views/PasswordResetView'
+ ],
function($, _, TemplateHelpers, AjaxHelpers, PasswordResetModel, PasswordResetView) {
+ describe('edx.student.account.PasswordResetView', function() {
+ var model = null,
+ view = null,
+ requests = null,
+ EMAIL = 'xsy@edx.org',
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/account/password',
+ fields: [{
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ placeholder: 'place@holder.org',
+ instructions: 'Enter your email.',
+ restrictions: {}
+ }]
+ };
- describe('edx.student.account.PasswordResetView', function() {
- var model = null,
- view = null,
- requests = null,
- EMAIL = 'xsy@edx.org',
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/account/password',
- fields: [{
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'text',
- required: true,
- placeholder: 'place@holder.org',
- instructions: 'Enter your email.',
- restrictions: {}
- }]
- };
-
- var createPasswordResetView = function(that) {
+ var createPasswordResetView = function(that) {
// Initialize the password reset model
- model = new PasswordResetModel({}, {
- url: FORM_DESCRIPTION.submit_url,
- method: FORM_DESCRIPTION.method
- });
+ model = new PasswordResetModel({}, {
+ url: FORM_DESCRIPTION.submit_url,
+ method: FORM_DESCRIPTION.method
+ });
// Initialize the password reset view
- view = new PasswordResetView({
- fields: FORM_DESCRIPTION.fields,
- model: model
- });
+ view = new PasswordResetView({
+ fields: FORM_DESCRIPTION.fields,
+ model: model
+ });
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
- };
+ requests = AjaxHelpers.requests(that);
+ };
- var submitEmail = function(validationSuccess) {
+ var submitEmail = function(validationSuccess) {
// Create a fake click event
- var clickEvent = $.Event('click');
+ var clickEvent = $.Event('click');
// Simulate manual entry of an email address
- $('#password-reset-email').val(EMAIL);
+ $('#password-reset-email').val(EMAIL);
// If validationSuccess isn't passed, we avoid
// spying on `view.validate` twice
- if ( !_.isUndefined(validationSuccess) ) {
+ if (!_.isUndefined(validationSuccess)) {
// Force validation to return as expected
- spyOn(view, 'validate').and.returnValue({
- isValid: validationSuccess,
- message: 'Submission was validated.'
- });
- }
+ spyOn(view, 'validate').and.returnValue({
+ isValid: validationSuccess,
+ message: 'Submission was validated.'
+ });
+ }
// Submit the email address
- view.submitForm(clickEvent);
- };
+ view.submitForm(clickEvent);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/password_reset');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/password_reset');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ });
- it('allows the user to request a new password', function() {
- createPasswordResetView(this);
+ it('allows the user to request a new password', function() {
+ createPasswordResetView(this);
// Submit the form, with successful validation
- submitEmail(true);
+ submitEmail(true);
// Verify that the client contacts the server with the expected data
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param({ email: EMAIL })
+ $.param({email: EMAIL})
);
// Respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Verify that the success message is visible
- expect($('.js-reset-success')).not.toHaveClass('hidden');
+ expect($('.js-reset-success')).not.toHaveClass('hidden');
// Verify that login form has loaded
- expect($('#login-form')).not.toHaveClass('hidden');
+ expect($('#login-form')).not.toHaveClass('hidden');
// Verify that password reset view has been removed
- expect($( view.el ).html().length).toEqual(0);
- });
+ expect($(view.el).html().length).toEqual(0);
+ });
- it('validates the email field', function() {
- createPasswordResetView(this);
+ it('validates the email field', function() {
+ createPasswordResetView(this);
// Submit the form, with successful validation
- submitEmail(true);
+ submitEmail(true);
// Verify that validation of the email field occurred
- expect(view.validate).toHaveBeenCalledWith($('#password-reset-email')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#password-reset-email')[0]);
// Verify that no submission errors are visible
- expect(view.$errors).toHaveClass('hidden');
- });
+ expect(view.$errors).toHaveClass('hidden');
+ });
- it('displays password reset validation errors', function() {
- createPasswordResetView(this);
+ it('displays password reset validation errors', function() {
+ createPasswordResetView(this);
// Submit the form, with failed validation
- submitEmail(false);
+ submitEmail(false);
// Verify that submission errors are visible
- expect(view.$errors).not.toHaveClass('hidden');
- });
+ expect(view.$errors).not.toHaveClass('hidden');
+ });
- it('displays an error if the server returns an error while sending a password reset email', function() {
- createPasswordResetView(this);
- submitEmail(true);
+ it('displays an error if the server returns an error while sending a password reset email', function() {
+ createPasswordResetView(this);
+ submitEmail(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests);
+ AjaxHelpers.respondWithError(requests);
// Expect that an error is displayed
- expect(view.$errors).not.toHaveClass('hidden');
+ expect(view.$errors).not.toHaveClass('hidden');
// If we try again and succeed, the error should go away
- submitEmail();
+ submitEmail();
// This time, respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the error is hidden
- expect(view.$errors).toHaveClass('hidden');
+ expect(view.$errors).toHaveClass('hidden');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/register_spec.js b/lms/static/js/spec/student_account/register_spec.js
index 2363af913e..d6ea9987e6 100644
--- a/lms/static/js/spec/student_account/register_spec.js
+++ b/lms/static/js/spec/student_account/register_spec.js
@@ -1,356 +1,355 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/student_account/models/RegisterModel',
- 'js/student_account/views/RegisterView'
- ],
+ 'jquery',
+ 'underscore',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/student_account/models/RegisterModel',
+ 'js/student_account/views/RegisterView'
+ ],
function($, _, TemplateHelpers, AjaxHelpers, RegisterModel, RegisterView) {
+ describe('edx.student.account.RegisterView', function() {
+ var model = null,
+ view = null,
+ requests = null,
+ authComplete = false,
+ PLATFORM_NAME = 'edX',
+ COURSE_ID = 'edX/DemoX/Fall',
+ USER_DATA = {
+ email: 'xsy@edx.org',
+ name: 'Xsy M. Education',
+ username: 'Xsy',
+ password: 'xsyisawesome',
+ level_of_education: 'p',
+ gender: 'm',
+ year_of_birth: 2014,
+ mailing_address: '141 Portland',
+ goals: 'To boldly learn what no letter of the alphabet has learned before',
+ honor_code: true
+ },
+ THIRD_PARTY_AUTH = {
+ currentProvider: null,
+ providers: [
+ {
+ id: 'oa2-google-oauth2',
+ name: 'Google',
+ iconClass: 'fa-google-plus',
+ loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
+ registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
+ },
+ {
+ id: 'oa2-facebook',
+ name: 'Facebook',
+ iconClass: 'fa-facebook',
+ loginUrl: '/auth/login/facebook/?auth_entry=account_login',
+ registerUrl: '/auth/login/facebook/?auth_entry=account_register'
+ }
+ ]
+ },
+ FORM_DESCRIPTION = {
+ method: 'post',
+ submit_url: '/user_api/v1/account/registration/',
+ fields: [
+ {
+ placeholder: 'username@domain.com',
+ name: 'email',
+ label: 'Email',
+ defaultValue: '',
+ type: 'email',
+ required: true,
+ instructions: 'Enter your email.',
+ restrictions: {}
+ },
+ {
+ placeholder: 'Jane Doe',
+ name: 'name',
+ label: 'Full Name',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ instructions: 'Enter your username.',
+ restrictions: {}
+ },
+ {
+ placeholder: 'JaneDoe',
+ name: 'username',
+ label: 'Username',
+ defaultValue: '',
+ type: 'text',
+ required: true,
+ instructions: 'Enter your username.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'password',
+ label: 'Password',
+ defaultValue: '',
+ type: 'password',
+ required: true,
+ instructions: 'Enter your password.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'level_of_education',
+ label: 'Highest Level of Education Completed',
+ defaultValue: '',
+ type: 'select',
+ options: [
+ {value: '', name: '--'},
+ {value: 'p', name: 'Doctorate'},
+ {value: 'm', name: "Master's or professional degree"},
+ {value: 'b', name: "Bachelor's degree"}
+ ],
+ required: false,
+ instructions: 'Select your education level.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'gender',
+ label: 'Gender',
+ defaultValue: '',
+ type: 'select',
+ options: [
+ {value: '', name: '--'},
+ {value: 'm', name: 'Male'},
+ {value: 'f', name: 'Female'},
+ {value: 'o', name: 'Other'}
+ ],
+ required: false,
+ instructions: 'Select your gender.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'year_of_birth',
+ label: 'Year of Birth',
+ defaultValue: '',
+ type: 'select',
+ options: [
+ {value: '', name: '--'},
+ {value: 1900, name: '1900'},
+ {value: 1950, name: '1950'},
+ {value: 2014, name: '2014'}
+ ],
+ required: false,
+ instructions: 'Select your year of birth.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'mailing_address',
+ label: 'Mailing Address',
+ defaultValue: '',
+ type: 'textarea',
+ required: false,
+ instructions: 'Enter your mailing address.',
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'goals',
+ label: 'Goals',
+ defaultValue: '',
+ type: 'textarea',
+ required: false,
+ instructions: "If you'd like, tell us why you're interested in edX.",
+ restrictions: {}
+ },
+ {
+ placeholder: '',
+ name: 'honor_code',
+ label: 'I agree to the
Terms of Service and Honor Code',
+ defaultValue: '',
+ type: 'checkbox',
+ required: true,
+ instructions: '',
+ restrictions: {}
+ }
+ ]
+ };
- describe('edx.student.account.RegisterView', function() {
- var model = null,
- view = null,
- requests = null,
- authComplete = false,
- PLATFORM_NAME = 'edX',
- COURSE_ID = 'edX/DemoX/Fall',
- USER_DATA = {
- email: 'xsy@edx.org',
- name: 'Xsy M. Education',
- username: 'Xsy',
- password: 'xsyisawesome',
- level_of_education: 'p',
- gender: 'm',
- year_of_birth: 2014,
- mailing_address: '141 Portland',
- goals: 'To boldly learn what no letter of the alphabet has learned before',
- honor_code: true
- },
- THIRD_PARTY_AUTH = {
- currentProvider: null,
- providers: [
- {
- id: 'oa2-google-oauth2',
- name: 'Google',
- iconClass: 'fa-google-plus',
- loginUrl: '/auth/login/google-oauth2/?auth_entry=account_login',
- registerUrl: '/auth/login/google-oauth2/?auth_entry=account_register'
- },
- {
- id: 'oa2-facebook',
- name: 'Facebook',
- iconClass: 'fa-facebook',
- loginUrl: '/auth/login/facebook/?auth_entry=account_login',
- registerUrl: '/auth/login/facebook/?auth_entry=account_register'
- }
- ]
- },
- FORM_DESCRIPTION = {
- method: 'post',
- submit_url: '/user_api/v1/account/registration/',
- fields: [
- {
- placeholder: 'username@domain.com',
- name: 'email',
- label: 'Email',
- defaultValue: '',
- type: 'email',
- required: true,
- instructions: 'Enter your email.',
- restrictions: {}
- },
- {
- placeholder: 'Jane Doe',
- name: 'name',
- label: 'Full Name',
- defaultValue: '',
- type: 'text',
- required: true,
- instructions: 'Enter your username.',
- restrictions: {}
- },
- {
- placeholder: 'JaneDoe',
- name: 'username',
- label: 'Username',
- defaultValue: '',
- type: 'text',
- required: true,
- instructions: 'Enter your username.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'password',
- label: 'Password',
- defaultValue: '',
- type: 'password',
- required: true,
- instructions: 'Enter your password.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'level_of_education',
- label: 'Highest Level of Education Completed',
- defaultValue: '',
- type: 'select',
- options: [
- {value: "", name: "--"},
- {value: "p", name: "Doctorate"},
- {value: "m", name: "Master's or professional degree"},
- {value: "b", name: "Bachelor's degree"}
- ],
- required: false,
- instructions: 'Select your education level.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'gender',
- label: 'Gender',
- defaultValue: '',
- type: 'select',
- options: [
- {value: "", name: "--"},
- {value: "m", name: "Male"},
- {value: "f", name: "Female"},
- {value: "o", name: "Other"}
- ],
- required: false,
- instructions: 'Select your gender.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'year_of_birth',
- label: 'Year of Birth',
- defaultValue: '',
- type: 'select',
- options: [
- {value: "", name: "--"},
- {value: 1900, name: "1900"},
- {value: 1950, name: "1950"},
- {value: 2014, name: "2014"}
- ],
- required: false,
- instructions: 'Select your year of birth.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'mailing_address',
- label: 'Mailing Address',
- defaultValue: '',
- type: 'textarea',
- required: false,
- instructions: 'Enter your mailing address.',
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'goals',
- label: 'Goals',
- defaultValue: '',
- type: 'textarea',
- required: false,
- instructions: "If you'd like, tell us why you're interested in edX.",
- restrictions: {}
- },
- {
- placeholder: '',
- name: 'honor_code',
- label: 'I agree to the
Terms of Service and Honor Code',
- defaultValue: '',
- type: 'checkbox',
- required: true,
- instructions: '',
- restrictions: {}
- }
- ]
- };
-
- var createRegisterView = function(that) {
+ var createRegisterView = function(that) {
// Initialize the register model
- model = new RegisterModel({}, {
- url: FORM_DESCRIPTION.submit_url,
- method: FORM_DESCRIPTION.method
- });
+ model = new RegisterModel({}, {
+ url: FORM_DESCRIPTION.submit_url,
+ method: FORM_DESCRIPTION.method
+ });
// Initialize the register view
- view = new RegisterView({
- fields: FORM_DESCRIPTION.fields,
- model: model,
- thirdPartyAuth: THIRD_PARTY_AUTH,
- platformName: PLATFORM_NAME
- });
+ view = new RegisterView({
+ fields: FORM_DESCRIPTION.fields,
+ model: model,
+ thirdPartyAuth: THIRD_PARTY_AUTH,
+ platformName: PLATFORM_NAME
+ });
// Spy on AJAX requests
- requests = AjaxHelpers.requests(that);
+ requests = AjaxHelpers.requests(that);
// Intercept events from the view
- authComplete = false;
- view.on("auth-complete", function() {
- authComplete = true;
- });
- };
+ authComplete = false;
+ view.on('auth-complete', function() {
+ authComplete = true;
+ });
+ };
- var submitForm = function(validationSuccess) {
+ var submitForm = function(validationSuccess) {
// Create a fake click event
- var clickEvent = $.Event('click');
+ var clickEvent = $.Event('click');
// Simulate manual entry of registration form data
- $('#register-email').val(USER_DATA.email);
- $('#register-name').val(USER_DATA.name);
- $('#register-username').val(USER_DATA.username);
- $('#register-password').val(USER_DATA.password);
- $('#register-level_of_education').val(USER_DATA.level_of_education);
- $('#register-gender').val(USER_DATA.gender);
- $('#register-year_of_birth').val(USER_DATA.year_of_birth);
- $('#register-mailing_address').val(USER_DATA.mailing_address);
- $('#register-goals').val(USER_DATA.goals);
+ $('#register-email').val(USER_DATA.email);
+ $('#register-name').val(USER_DATA.name);
+ $('#register-username').val(USER_DATA.username);
+ $('#register-password').val(USER_DATA.password);
+ $('#register-level_of_education').val(USER_DATA.level_of_education);
+ $('#register-gender').val(USER_DATA.gender);
+ $('#register-year_of_birth').val(USER_DATA.year_of_birth);
+ $('#register-mailing_address').val(USER_DATA.mailing_address);
+ $('#register-goals').val(USER_DATA.goals);
// Check the honor code checkbox
- $('#register-honor_code').prop('checked', USER_DATA.honor_code);
+ $('#register-honor_code').prop('checked', USER_DATA.honor_code);
// If validationSuccess isn't passed, we avoid
// spying on `view.validate` twice
- if ( !_.isUndefined(validationSuccess) ) {
+ if (!_.isUndefined(validationSuccess)) {
// Force validation to return as expected
- spyOn(view, 'validate').and.returnValue({
- isValid: validationSuccess,
- message: 'Submission was validated.'
- });
- }
+ spyOn(view, 'validate').and.returnValue({
+ isValid: validationSuccess,
+ message: 'Submission was validated.'
+ });
+ }
// Submit the email address
- view.submitForm(clickEvent);
- };
+ view.submitForm(clickEvent);
+ };
- beforeEach(function() {
- setFixtures('
');
- TemplateHelpers.installTemplate('templates/student_account/register');
- TemplateHelpers.installTemplate('templates/student_account/form_field');
- });
+ beforeEach(function() {
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/student_account/register');
+ TemplateHelpers.installTemplate('templates/student_account/form_field');
+ });
- it('registers a new user', function() {
- createRegisterView(this);
+ it('registers a new user', function() {
+ createRegisterView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Verify that the client contacts the server with the expected data
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param( USER_DATA )
+ $.param(USER_DATA)
);
// Respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Verify that auth complete is triggered
- expect(authComplete).toBe(true);
+ expect(authComplete).toBe(true);
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
- });
+ expect(view.$submitButton).toHaveAttr('disabled');
+ });
- it('sends analytics info containing the enrolled course ID', function() {
- var expectedData;
+ it('sends analytics info containing the enrolled course ID', function() {
+ var expectedData;
- createRegisterView(this);
+ createRegisterView(this);
// Simulate that the user is attempting to enroll in a course
// by setting the course_id query string param.
- spyOn($, 'url').and.callFake(function( param ) {
- if (param === '?course_id') {
- return encodeURIComponent( COURSE_ID );
- }
- });
+ spyOn($, 'url').and.callFake(function(param) {
+ if (param === '?course_id') {
+ return encodeURIComponent(COURSE_ID);
+ }
+ });
// Attempt to register
- submitForm( true );
+ submitForm(true);
// Verify that the client sent the course ID for analytics
- expectedData = {course_id: COURSE_ID};
- $.extend(expectedData, USER_DATA);
+ expectedData = {course_id: COURSE_ID};
+ $.extend(expectedData, USER_DATA);
- AjaxHelpers.expectRequest(
+ AjaxHelpers.expectRequest(
requests, 'POST',
FORM_DESCRIPTION.submit_url,
- $.param( expectedData )
+ $.param(expectedData)
);
- });
+ });
- it('displays third-party auth registration buttons', function() {
- createRegisterView(this);
+ it('displays third-party auth registration buttons', function() {
+ createRegisterView(this);
// Verify that Google and Facebook registration buttons are displayed
- expect($('.button-oa2-google-oauth2')).toBeVisible();
- expect($('.button-oa2-facebook')).toBeVisible();
- });
+ expect($('.button-oa2-google-oauth2')).toBeVisible();
+ expect($('.button-oa2-facebook')).toBeVisible();
+ });
- it('validates registration form fields', function() {
- createRegisterView(this);
+ it('validates registration form fields', function() {
+ createRegisterView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Verify that validation of form fields occurred
- expect(view.validate).toHaveBeenCalledWith($('#register-email')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#register-name')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#register-username')[0]);
- expect(view.validate).toHaveBeenCalledWith($('#register-password')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-email')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-name')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-username')[0]);
+ expect(view.validate).toHaveBeenCalledWith($('#register-password')[0]);
// Verify that no submission errors are visible
- expect(view.$errors).toHaveClass('hidden');
+ expect(view.$errors).toHaveClass('hidden');
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
- });
+ expect(view.$submitButton).toHaveAttr('disabled');
+ });
- it('displays registration form validation errors', function() {
- createRegisterView(this);
+ it('displays registration form validation errors', function() {
+ createRegisterView(this);
// Submit the form, with failed validation
- submitForm(false);
+ submitForm(false);
// Verify that submission errors are visible
- expect(view.$errors).not.toHaveClass('hidden');
+ expect(view.$errors).not.toHaveClass('hidden');
// Expect that auth complete is NOT triggered
- expect(authComplete).toBe(false);
+ expect(authComplete).toBe(false);
// Form button should be re-enabled on error.
- expect(view.$submitButton).not.toHaveAttr('disabled');
- });
+ expect(view.$submitButton).not.toHaveAttr('disabled');
+ });
- it('displays an error if the server returns an error while registering', function() {
- createRegisterView(this);
+ it('displays an error if the server returns an error while registering', function() {
+ createRegisterView(this);
// Submit the form, with successful validation
- submitForm(true);
+ submitForm(true);
// Simulate an error from the LMS servers
- AjaxHelpers.respondWithError(requests);
+ AjaxHelpers.respondWithError(requests);
// Expect that an error is displayed and that auth complete is NOT triggered
- expect(view.$errors).not.toHaveClass('hidden');
- expect(authComplete).toBe(false);
+ expect(view.$errors).not.toHaveClass('hidden');
+ expect(authComplete).toBe(false);
// If we try again and succeed, the error should go away
- submitForm();
+ submitForm();
// This time, respond with status code 200
- AjaxHelpers.respondWithJson(requests, {});
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the error is hidden and that auth complete is triggered
- expect(view.$errors).toHaveClass('hidden');
- expect(authComplete).toBe(true);
+ expect(view.$errors).toHaveClass('hidden');
+ expect(authComplete).toBe(true);
// Form button should be disabled on success.
- expect(view.$submitButton).toHaveAttr('disabled');
+ expect(view.$submitButton).toHaveAttr('disabled');
+ });
});
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/spec/student_account/shoppingcart_spec.js b/lms/static/js/spec/student_account/shoppingcart_spec.js
index f786bb96b3..69ed04ba7c 100644
--- a/lms/static/js/spec/student_account/shoppingcart_spec.js
+++ b/lms/static/js/spec/student_account/shoppingcart_spec.js
@@ -2,11 +2,10 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
function(AjaxHelpers, ShoppingCartInterface) {
'use strict';
- describe( 'ShoppingCartInterface', function() {
-
- var COURSE_KEY = "edX/DemoX/Fall",
- ADD_COURSE_URL = "/shoppingcart/add/course/edX/DemoX/Fall/",
- FORWARD_URL = "/shoppingcart/";
+ describe('ShoppingCartInterface', function() {
+ var COURSE_KEY = 'edX/DemoX/Fall',
+ ADD_COURSE_URL = '/shoppingcart/add/course/edX/DemoX/Fall/',
+ FORWARD_URL = '/shoppingcart/';
beforeEach(function() {
// Mock the redirect call
@@ -15,33 +14,33 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/student_account
it('adds a course to the cart', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to add a course to the cart
- ShoppingCartInterface.addCourseToCart( COURSE_KEY );
+ ShoppingCartInterface.addCourseToCart(COURSE_KEY);
// Expect that the correct request was made to the server
- AjaxHelpers.expectRequest( requests, 'POST', ADD_COURSE_URL );
+ AjaxHelpers.expectRequest(requests, 'POST', ADD_COURSE_URL);
// Simulate a successful response from the server
- AjaxHelpers.respondWithJson( requests, {} );
+ AjaxHelpers.respondWithJson(requests, {});
// Expect that the user was redirected to the shopping cart
- expect( ShoppingCartInterface.redirect ).toHaveBeenCalledWith( FORWARD_URL );
+ expect(ShoppingCartInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
it('redirects the user on a server error', function() {
// Spy on Ajax requests
- var requests = AjaxHelpers.requests( this );
+ var requests = AjaxHelpers.requests(this);
// Attempt to add a course to the cart
- ShoppingCartInterface.addCourseToCart( COURSE_KEY );
+ ShoppingCartInterface.addCourseToCart(COURSE_KEY);
// Simulate an error response from the server
- AjaxHelpers.respondWithError( requests );
+ AjaxHelpers.respondWithError(requests);
// Expect that the user was redirected to the shopping cart
- expect( ShoppingCartInterface.redirect ).toHaveBeenCalledWith( FORWARD_URL );
+ expect(ShoppingCartInterface.redirect).toHaveBeenCalledWith(FORWARD_URL);
});
});
}
diff --git a/lms/static/js/spec/student_profile/badge_list_container_spec.js b/lms/static/js/spec/student_profile/badge_list_container_spec.js
index bd4592b2ff..63bd272059 100644
--- a/lms/static/js/spec/student_profile/badge_list_container_spec.js
+++ b/lms/static/js/spec/student_profile/badge_list_container_spec.js
@@ -1,17 +1,16 @@
define([
- 'backbone',
- 'jquery',
- 'underscore',
- 'URI',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'edx-ui-toolkit/js/pagination/paging-collection',
- 'js/spec/student_profile/helpers',
- 'js/student_profile/views/badge_list_container'
- ],
+ 'backbone',
+ 'jquery',
+ 'underscore',
+ 'URI',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'edx-ui-toolkit/js/pagination/paging-collection',
+ 'js/spec/student_profile/helpers',
+ 'js/student_profile/views/badge_list_container'
+],
function(Backbone, $, _, URI, AjaxHelpers, PagingCollection, LearnerProfileHelpers, BadgeListContainer) {
'use strict';
- describe('edx.user.BadgeListContainer', function () {
-
+ describe('edx.user.BadgeListContainer', function() {
var view, requests;
var createView = function(requests, pageNum, badgeListObject) {
@@ -23,7 +22,7 @@ define([
var badgeCollection = new BadgeCollection();
badgeCollection.url = '/api/badges/v1/assertions/user/staff/';
var models = [];
- _.each(_.range(badgeListObject.count), function (idx) {
+ _.each(_.range(badgeListObject.count), function(idx) {
models.push(LearnerProfileHelpers.makeBadge(idx));
});
badgeListObject.results = models;
@@ -40,11 +39,11 @@ define([
return badgeListContainer;
};
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
});
- it('displays all badges', function () {
+ it('displays all badges', function() {
requests = AjaxHelpers.requests(this);
view = createView(requests, 1, {
count: 30,
@@ -59,7 +58,7 @@ define([
expect(badges.length).toBe(30);
});
- it('displays placeholder on last page', function () {
+ it('displays placeholder on last page', function() {
requests = AjaxHelpers.requests(this);
view = createView(requests, 3, {
count: 30,
@@ -74,7 +73,7 @@ define([
expect(placeholder.length).toBe(1);
});
- it('does not display placeholder on first page', function () {
+ it('does not display placeholder on first page', function() {
requests = AjaxHelpers.requests(this);
view = createView(requests, 1, {
count: 30,
@@ -88,7 +87,6 @@ define([
var placeholder = view.$el.find('span.accomplishment-placeholder');
expect(placeholder.length).toBe(0);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/badge_list_view_spec.js b/lms/static/js/spec/student_profile/badge_list_view_spec.js
index b9a088f3fe..f097100186 100644
--- a/lms/static/js/spec/student_profile/badge_list_view_spec.js
+++ b/lms/static/js/spec/student_profile/badge_list_view_spec.js
@@ -1,29 +1,28 @@
define([
- 'backbone',
- 'jquery',
- 'underscore',
- 'edx-ui-toolkit/js/pagination/paging-collection',
- 'js/spec/student_profile/helpers',
- 'js/student_profile/views/badge_list_view'
- ],
- function (Backbone, $, _, PagingCollection, LearnerProfileHelpers, BadgeListView) {
- "use strict";
- describe("edx.user.BadgeListView", function () {
-
+ 'backbone',
+ 'jquery',
+ 'underscore',
+ 'edx-ui-toolkit/js/pagination/paging-collection',
+ 'js/spec/student_profile/helpers',
+ 'js/student_profile/views/badge_list_view'
+],
+ function(Backbone, $, _, PagingCollection, LearnerProfileHelpers, BadgeListView) {
+ 'use strict';
+ describe('edx.user.BadgeListView', function() {
var view;
- var createView = function (badges, pages, page, hasNextPage) {
+ var createView = function(badges, pages, page, hasNextPage) {
var badgeCollection = new PagingCollection();
- badgeCollection.url = "/api/badges/v1/assertions/user/staff/";
+ badgeCollection.url = '/api/badges/v1/assertions/user/staff/';
var models = [];
- _.each(badges, function (element) {
+ _.each(badges, function(element) {
models.push(new Backbone.Model(element));
});
badgeCollection.models = models;
badgeCollection.length = badges.length;
badgeCollection.currentPage = page;
badgeCollection.totalPages = pages;
- badgeCollection.hasNextPage = function () {
+ badgeCollection.hasNextPage = function() {
return hasNextPage;
};
var badge_list = new BadgeListView({
@@ -33,35 +32,35 @@ define([
return badge_list;
};
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
});
-
- it("there is a single row if there is only one badge", function () {
+
+ it('there is a single row if there is only one badge', function() {
view = createView([LearnerProfileHelpers.makeBadge(1)], 1, 1, false);
view.render();
var rows = view.$el.find('div.row');
expect(rows.length).toBe(1);
});
- it("accomplishments placeholder is visible on a last page", function () {
+ it('accomplishments placeholder is visible on a last page', function() {
view = createView([LearnerProfileHelpers.makeBadge(1)], 2, 2, false);
view.render();
var placeholder = view.$el.find('span.accomplishment-placeholder');
expect(placeholder.length).toBe(1);
});
- it("accomplishments placeholder to be not visible on a first page", function () {
+ it('accomplishments placeholder to be not visible on a first page', function() {
view = createView([LearnerProfileHelpers.makeBadge(1)], 1, 2, true);
view.render();
var placeholder = view.$el.find('span.accomplishment-placeholder');
expect(placeholder.length).toBe(0);
});
- it("badges are in two columns (checked by counting rows for a known number of badges)", function () {
+ it('badges are in two columns (checked by counting rows for a known number of badges)', function() {
var badges = [];
- _.each(_.range(4), function (item) {
- badges.push(LearnerProfileHelpers.makeBadge(item));
+ _.each(_.range(4), function(item) {
+ badges.push(LearnerProfileHelpers.makeBadge(item));
});
view = createView(badges, 1, 2, true);
view.render();
@@ -70,7 +69,6 @@ define([
var rows = view.$el.find('div.row');
expect(rows.length).toBe(2);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/badge_view_spec.js b/lms/static/js/spec/student_profile/badge_view_spec.js
index d40258fcd7..35ad00ea26 100644
--- a/lms/static/js/spec/student_profile/badge_view_spec.js
+++ b/lms/static/js/spec/student_profile/badge_view_spec.js
@@ -2,13 +2,12 @@ define(['backbone', 'jquery', 'underscore',
'js/spec/student_profile/helpers',
'js/student_profile/views/badge_view'
],
- function (Backbone, $, _, LearnerProfileHelpers, BadgeView) {
- "use strict";
- describe("edx.user.BadgeView", function () {
-
+ function(Backbone, $, _, LearnerProfileHelpers, BadgeView) {
+ 'use strict';
+ describe('edx.user.BadgeView', function() {
var view, badge;
- var createView = function (ownProfile) {
+ var createView = function(ownProfile) {
badge = LearnerProfileHelpers.makeBadge(1);
var options = {
'model': new Backbone.Model(badge),
@@ -23,26 +22,26 @@ define(['backbone', 'jquery', 'underscore',
return view;
};
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
$('.badges-modal').remove();
});
- it("profile of other has no share button", function () {
+ it('profile of other has no share button', function() {
view = createView(false);
expect(view.context.ownProfile).toBeFalsy();
expect(view.$el.find('button.share-button').length).toBe(0);
});
- it("own profile has share button", function () {
+ it('own profile has share button', function() {
view = createView(true);
expect(view.context.ownProfile).toBeTruthy();
expect(view.$el.find('button.share-button').length).toBe(1);
});
- it("click on share button calls createModal function", function () {
+ it('click on share button calls createModal function', function() {
view = createView(true);
- spyOn(view, "createModal");
+ spyOn(view, 'createModal');
view.delegateEvents();
expect(view.context.ownProfile).toBeTruthy();
var shareButton = view.$el.find('button.share-button');
@@ -52,53 +51,52 @@ define(['backbone', 'jquery', 'underscore',
expect(view.createModal).toHaveBeenCalled();
});
- it("click on share button calls shows the dialog", function (done) {
+ it('click on share button calls shows the dialog', function(done) {
view = createView(true);
expect(view.context.ownProfile).toBeTruthy();
var shareButton = view.$el.find('button.share-button');
expect(shareButton.length).toBe(1);
var modalElement = $('.badges-modal');
expect(modalElement.length).toBe(0);
- expect(modalElement.is(":visible")).toBeFalsy();
+ expect(modalElement.is(':visible')).toBeFalsy();
shareButton.click();
// Note: this element should have appeared in the dom during: shareButton.click();
modalElement = $('.badges-modal');
- jasmine.waitUntil(function () {
- return modalElement.is(":visible");
+ jasmine.waitUntil(function() {
+ return modalElement.is(':visible');
}).always(done);
});
- var testBadgeNameIsDisplayed = function (ownProfile) {
+ var testBadgeNameIsDisplayed = function(ownProfile) {
view = createView(ownProfile);
- var badgeDiv = view.$el.find(".badge-name");
+ var badgeDiv = view.$el.find('.badge-name');
expect(badgeDiv.length).toBeTruthy();
expect(badgeDiv.is(':visible')).toBe(true);
expect(_.count(badgeDiv.html(), badge.badge_class.display_name)).toBeTruthy();
};
- it("test badge name is displayed for own profile", function () {
+ it('test badge name is displayed for own profile', function() {
testBadgeNameIsDisplayed(true);
});
- it("test badge name is displayed for other profile", function () {
+ it('test badge name is displayed for other profile', function() {
testBadgeNameIsDisplayed(false);
});
- var testBadgeIconIsDisplayed = function (ownProfile) {
+ var testBadgeIconIsDisplayed = function(ownProfile) {
view = createView(ownProfile);
- var badgeImg = view.$el.find("img.badge");
+ var badgeImg = view.$el.find('img.badge');
expect(badgeImg.length).toBe(1);
expect(badgeImg.attr('src')).toEqual(badge.image_url);
};
- it("test badge icon is displayed for own profile", function () {
+ it('test badge icon is displayed for own profile', function() {
testBadgeIconIsDisplayed(true);
});
- it("test badge icon is displayed for other profile", function () {
+ it('test badge icon is displayed for other profile', function() {
testBadgeIconIsDisplayed(false);
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/helpers.js b/lms/static/js/spec/student_profile/helpers.js
index 989cfbafe2..e334923541 100644
--- a/lms/static/js/spec/student_profile/helpers.js
+++ b/lms/static/js/spec/student_profile/helpers.js
@@ -14,11 +14,9 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
expect($($element.find('.image-frame')[0]).attr('src')).toBe(view.imageUrl());
} else if (view.fieldValue()) {
expect(view.fieldValue()).toBe(view.modelValue());
-
} else if ('optionForValue' in view) {
expect($($element.find('.u-field-value .u-field-value-readonly')[0]).text()).toBe(view.displayValue(view.modelValue()));
-
- }else {
+ } else {
expect($($element.find('.u-field-value .u-field-value-readonly')[0]).text()).toBe(view.modelValue());
}
} else {
@@ -27,7 +25,6 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
var expectProfilePrivacyFieldTobeRendered = function(learnerProfileView, othersProfile) {
-
var accountPrivacyElement = learnerProfileView.$('.wrapper-profile-field-account-privacy');
var privacyFieldElement = $(accountPrivacyElement).find('.u-field');
@@ -40,14 +37,13 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
var expectSectionOneTobeRendered = function(learnerProfileView) {
-
var sectionOneFieldElements = $(learnerProfileView.$('.wrapper-profile-section-one')).find('.u-field');
expect(sectionOneFieldElements.length).toBe(4);
expectProfileElementContainsField(sectionOneFieldElements[0], learnerProfileView.options.profileImageFieldView);
expectProfileElementContainsField(sectionOneFieldElements[1], learnerProfileView.options.usernameFieldView);
- _.each(_.rest(sectionOneFieldElements, 2) , function (sectionFieldElement, fieldIndex) {
+ _.each(_.rest(sectionOneFieldElements, 2), function(sectionFieldElement, fieldIndex) {
expectProfileElementContainsField(
sectionFieldElement,
learnerProfileView.options.sectionOneFieldViews[fieldIndex]
@@ -56,13 +52,12 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
};
var expectSectionTwoTobeRendered = function(learnerProfileView) {
-
var sectionTwoElement = learnerProfileView.$('.wrapper-profile-section-two');
var sectionTwoFieldElements = $(sectionTwoElement).find('.u-field');
expect(sectionTwoFieldElements.length).toBe(learnerProfileView.options.sectionTwoFieldViews.length);
- _.each(sectionTwoFieldElements, function (sectionFieldElement, fieldIndex) {
+ _.each(sectionTwoFieldElements, function(sectionFieldElement, fieldIndex) {
expectProfileElementContainsField(
sectionFieldElement,
learnerProfileView.options.sectionTwoFieldViews[fieldIndex]
@@ -70,13 +65,13 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
});
};
- var expectProfileSectionsAndFieldsToBeRendered = function (learnerProfileView, othersProfile) {
+ var expectProfileSectionsAndFieldsToBeRendered = function(learnerProfileView, othersProfile) {
expectProfilePrivacyFieldTobeRendered(learnerProfileView, othersProfile);
expectSectionOneTobeRendered(learnerProfileView);
expectSectionTwoTobeRendered(learnerProfileView);
};
- var expectLimitedProfileSectionsAndFieldsToBeRendered = function (learnerProfileView, othersProfile) {
+ var expectLimitedProfileSectionsAndFieldsToBeRendered = function(learnerProfileView, othersProfile) {
expectProfilePrivacyFieldTobeRendered(learnerProfileView, othersProfile);
var sectionOneFieldElements = $(learnerProfileView.$('.wrapper-profile-section-one')).find('.u-field');
@@ -140,16 +135,16 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var expectPage = function(learnerProfileView, pageData) {
var badgeListContainer = learnerProfileView.$el.find('#tabpanel-accomplishments');
var index = badgeListContainer.find('span.search-count').text().trim();
- expect(index).toBe("Showing " + (pageData.start + 1) + "-" + (pageData.start + pageData.results.length) +
- " out of " + pageData.count + " total");
- expect(badgeListContainer.find('.current-page').text()).toBe("" + pageData.current_page);
+ expect(index).toBe('Showing ' + (pageData.start + 1) + '-' + (pageData.start + pageData.results.length) +
+ ' out of ' + pageData.count + ' total');
+ expect(badgeListContainer.find('.current-page').text()).toBe('' + pageData.current_page);
_.each(pageData.results, function(badge) {
- expect($(".badge-display:contains(" + badge.badge_class.display_name + ")").length).toBe(1);
+ expect($('.badge-display:contains(' + badge.badge_class.display_name + ')').length).toBe(1);
});
};
var expectBadgeLoadingErrorIsRendered = function(learnerProfileView) {
- var errorMessage = learnerProfileView.$el.find(".badge-set-display").text();
+ var errorMessage = learnerProfileView.$el.find('.badge-set-display').text();
expect(errorMessage).toBe(
'Your request could not be completed. Reload the page and try again. If the issue persists, click the ' +
'Help tab to report the problem.'
@@ -166,7 +161,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var firstPageBadges = {
count: 30,
previous: null,
- next: "/arbitrary/url",
+ next: '/arbitrary/url',
num_pages: 3,
start: 0,
current_page: 1,
@@ -175,8 +170,8 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var secondPageBadges = {
count: 30,
- previous: "/arbitrary/url",
- next: "/arbitrary/url",
+ previous: '/arbitrary/url',
+ next: '/arbitrary/url',
num_pages: 3,
start: 10,
current_page: 2,
@@ -185,7 +180,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
var thirdPageBadges = {
count: 30,
- previous: "/arbitrary/url",
+ previous: '/arbitrary/url',
num_pages: 3,
next: null,
start: 20,
@@ -193,20 +188,20 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
results: []
};
- function makeBadge (num) {
+ function makeBadge(num) {
return {
- "badge_class": {
- "slug": "test_slug_" + num,
- "issuing_component": "test_component",
- "display_name": "Test Badge " + num,
- "course_id": null,
- "description": "Yay! It's a test badge.",
- "criteria": "https://example.com/syllabus",
- "image_url": "http://localhost:8000/media/badge_classes/test_lMB9bRw.png"
+ 'badge_class': {
+ 'slug': 'test_slug_' + num,
+ 'issuing_component': 'test_component',
+ 'display_name': 'Test Badge ' + num,
+ 'course_id': null,
+ 'description': "Yay! It's a test badge.",
+ 'criteria': 'https://example.com/syllabus',
+ 'image_url': 'http://localhost:8000/media/badge_classes/test_lMB9bRw.png'
},
- "image_url": "http://example.com/image.png",
- "assertion_url": "http://example.com/example.json",
- "created_at": "2015-12-03T16:25:57.676113Z"
+ 'image_url': 'http://example.com/image.png',
+ 'assertion_url': 'http://example.com/example.json',
+ 'created_at': '2015-12-03T16:25:57.676113Z'
};
}
@@ -223,10 +218,10 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
});
var emptyBadges = {
- "count": 0,
- "previous": null,
- "num_pages": 1,
- "results": []
+ 'count': 0,
+ 'previous': null,
+ 'num_pages': 1,
+ 'results': []
};
return {
diff --git a/lms/static/js/spec/student_profile/learner_profile_factory_spec.js b/lms/static/js/spec/student_profile/learner_profile_factory_spec.js
index 961d818f05..7bc6b23e90 100644
--- a/lms/static/js/spec/student_profile/learner_profile_factory_spec.js
+++ b/lms/static/js/spec/student_profile/learner_profile_factory_spec.js
@@ -10,19 +10,18 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
'js/student_profile/views/learner_profile_factory',
'js/views/message_banner'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers, FieldViews,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers, FieldViews,
UserAccountModel, UserPreferencesModel, LearnerProfileView, LearnerProfileFields, LearnerProfilePage) {
'use strict';
- describe("edx.user.LearnerProfileFactory", function () {
-
+ describe('edx.user.LearnerProfileFactory', function() {
var requests;
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/student_profile/student_profile.html');
});
- afterEach(function () {
+ afterEach(function() {
Backbone.history.stop();
});
@@ -48,7 +47,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
};
- it("renders the full profile for a user", function() {
+ it('renders the full profile for a user', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true),
@@ -60,7 +59,6 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
it("renders the limited profile for undefined 'year_of_birth'", function() {
-
var context = createProfilePage(true, {year_of_birth: '', requires_parental_consent: true}),
learnerProfileView = context.learnerProfileView;
@@ -68,7 +66,6 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
it("doesn't show the mode toggle if badges are disabled", function() {
-
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: false}),
@@ -80,7 +77,6 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
it("doesn't show the mode toggle if badges fail to fetch", function() {
-
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: false}),
@@ -91,8 +87,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("renders the mode toggle if there are badges", function() {
-
+ it('renders the mode toggle if there are badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -105,8 +100,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectTabbedViewToBeShown(tabbedView);
});
- it("renders the mode toggle if badges enabled but none exist", function() {
-
+ it('renders the mode toggle if badges enabled but none exist', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -119,8 +113,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectTabbedViewToBeShown(tabbedView);
});
- it("displays the badges when the accomplishments toggle is selected", function () {
-
+ it('displays the badges when the accomplishments toggle is selected', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -138,8 +131,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("displays a placeholder on the last page of badges", function () {
-
+ it('displays a placeholder on the last page of badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -157,8 +149,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("displays a placeholder when the accomplishments toggle is selected and no badges exist", function () {
-
+ it('displays a placeholder when the accomplishments toggle is selected and no badges exist', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -176,7 +167,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectBadgesHidden(learnerProfileView);
});
- it("shows a paginated list of badges", function() {
+ it('shows a paginated list of badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -192,7 +183,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
LearnerProfileHelpers.expectPage(learnerProfileView, LearnerProfileHelpers.firstPageBadges);
});
- it("allows forward and backward navigation of badges", function () {
+ it('allows forward and backward navigation of badges', function() {
requests = AjaxHelpers.requests(this);
var context = createProfilePage(true, {accomplishments_shared: true}),
@@ -226,8 +217,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
- it("renders the limited profile for under 13 users", function() {
-
+ it('renders the limited profile for under 13 users', function() {
var context = createProfilePage(
true,
{year_of_birth: new Date().getFullYear() - 10, requires_parental_consent: true}
diff --git a/lms/static/js/spec/student_profile/learner_profile_fields_spec.js b/lms/static/js/spec/student_profile/learner_profile_fields_spec.js
index 712f838d5e..013630e351 100644
--- a/lms/static/js/spec/student_profile/learner_profile_fields_spec.js
+++ b/lms/static/js/spec/student_profile/learner_profile_fields_spec.js
@@ -8,17 +8,16 @@ define(['backbone',
'js/student_profile/views/learner_profile_fields',
'js/views/message_banner'
],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, UserAccountModel, LearnerProfileFields,
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, UserAccountModel, LearnerProfileFields,
MessageBannerView) {
'use strict';
- describe("edx.user.LearnerProfileFields", function () {
-
+ describe('edx.user.LearnerProfileFields', function() {
var MOCK_YEAR_OF_BIRTH = 1989;
var MOCK_IMAGE_MAX_BYTES = 64;
var MOCK_IMAGE_MIN_BYTES = 16;
- var createImageView = function (options) {
+ var createImageView = function(options) {
var yearOfBirth = _.isUndefined(options.yearOfBirth) ? MOCK_YEAR_OF_BIRTH : options.yearOfBirth;
var imageMaxBytes = _.isUndefined(options.imageMaxBytes) ? MOCK_IMAGE_MAX_BYTES : options.imageMaxBytes;
var imageMinBytes = _.isUndefined(options.imageMinBytes) ? MOCK_IMAGE_MIN_BYTES : options.imageMinBytes;
@@ -41,7 +40,7 @@ define(['backbone',
return new LearnerProfileFields.ProfileImageFieldView({
model: accountSettingsModel,
- valueAttribute: "profile_image",
+ valueAttribute: 'profile_image',
editable: options.ownProfile,
messageView: messageView,
imageMaxBytes: imageMaxBytes,
@@ -51,27 +50,27 @@ define(['backbone',
});
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/student_profile/student_profile.html');
TemplateHelpers.installTemplate('templates/student_profile/learner_profile');
TemplateHelpers.installTemplate('templates/fields/field_image');
- TemplateHelpers.installTemplate("templates/fields/message_banner");
+ TemplateHelpers.installTemplate('templates/fields/message_banner');
});
- afterEach(function () {
+ afterEach(function() {
// image_field.js's window.onBeforeUnload breaks Karma in Chrome, clean it up after each test
$(window).off('beforeunload');
});
- var createFakeImageFile = function (size) {
+ var createFakeImageFile = function(size) {
var fileFakeData = 'i63ljc6giwoskyb9x5sw0169bdcmcxr3cdz8boqv0lik971972cmd6yknvcxr5sw0nvc169bdcmcxsdf';
return new Blob(
- [ fileFakeData.substr(0, size) ],
- { type: 'image/jpg' }
+ [fileFakeData.substr(0, size)],
+ {type: 'image/jpg'}
);
};
- var initializeUploader = function (view) {
+ var initializeUploader = function(view) {
view.$('.upload-button-input').fileupload({
url: Helpers.IMAGE_UPLOAD_API_URL,
type: 'POST',
@@ -81,24 +80,22 @@ define(['backbone',
});
};
- describe("ProfileImageFieldView", function () {
-
- var verifyImageUploadButtonMessage = function (view, inProgress) {
+ describe('ProfileImageFieldView', function() {
+ var verifyImageUploadButtonMessage = function(view, inProgress) {
var iconName = inProgress ? 'fa-spinner' : 'fa-camera';
var message = inProgress ? view.titleUploading : view.uploadButtonTitle();
expect(view.$('.upload-button-icon span').attr('class')).toContain(iconName);
expect(view.$('.upload-button-title').text().trim()).toBe(message);
};
- var verifyImageRemoveButtonMessage = function (view, inProgress) {
+ var verifyImageRemoveButtonMessage = function(view, inProgress) {
var iconName = inProgress ? 'fa-spinner' : 'fa-remove';
var message = inProgress ? view.titleRemoving : view.removeButtonTitle();
expect(view.$('.remove-button-icon span').attr('class')).toContain(iconName);
expect(view.$('.remove-button-title').text().trim()).toBe(message);
};
- it("can upload profile image", function() {
-
+ it('can upload profile image', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -143,8 +140,7 @@ define(['backbone',
verifyImageUploadButtonMessage(imageView, false);
});
- it("can remove profile image", function() {
-
+ it('can remove profile image', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -177,7 +173,6 @@ define(['backbone',
});
it("can't remove default profile image", function() {
-
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -193,7 +188,6 @@ define(['backbone',
});
it("can't upload image having size greater than max size", function() {
-
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
@@ -221,7 +215,6 @@ define(['backbone',
});
it("can't upload and remove image if parental consent required", function() {
-
var imageView = createImageView({ownProfile: true, hasImage: false, yearOfBirth: ''});
imageView.render();
@@ -239,7 +232,6 @@ define(['backbone',
});
it("can't upload and remove image on others profile", function() {
-
var imageView = createImageView({ownProfile: false});
imageView.render();
@@ -256,7 +248,7 @@ define(['backbone',
expect(imageView.clickedRemoveButton).not.toHaveBeenCalled();
});
- it("shows message if we try to navigate away during image upload/remove", function() {
+ it('shows message if we try to navigate away during image upload/remove', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
spyOn(imageView, 'onBeforeUnload');
imageView.render();
@@ -274,7 +266,7 @@ define(['backbone',
expect(imageView.onBeforeUnload).toHaveBeenCalled();
});
- it("shows error message for HTTP 500", function() {
+ it('shows error message for HTTP 500', function() {
var imageView = createImageView({ownProfile: true, hasImage: false});
imageView.render();
diff --git a/lms/static/js/spec/student_profile/learner_profile_view_spec.js b/lms/static/js/spec/student_profile/learner_profile_view_spec.js
index f455011cc4..518a27c404 100644
--- a/lms/static/js/spec/student_profile/learner_profile_view_spec.js
+++ b/lms/static/js/spec/student_profile/learner_profile_view_spec.js
@@ -15,15 +15,13 @@ define(['backbone',
'js/student_account/views/account_settings_fields',
'js/views/message_banner'
],
- function (Backbone, $, _, PagingCollection, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers,
+ function(Backbone, $, _, PagingCollection, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers,
FieldViews, UserAccountModel, AccountPreferencesModel, LearnerProfileFields, LearnerProfileView,
BadgeListContainer, AccountSettingsFieldViews, MessageBannerView) {
'use strict';
- describe("edx.user.LearnerProfileView", function () {
-
- var createLearnerProfileView = function (ownProfile, accountPrivacy, profileIsPublic) {
-
+ describe('edx.user.LearnerProfileView', function() {
+ var createLearnerProfileView = function(ownProfile, accountPrivacy, profileIsPublic) {
var accountSettingsModel = new UserAccountModel();
accountSettingsModel.set(Helpers.createAccountSettingsData());
accountSettingsModel.set({'profile_is_public': profileIsPublic});
@@ -42,7 +40,7 @@ define(['backbone',
editable: 'always',
showMessages: false,
title: 'edX learners can see my:',
- valueAttribute: "account_privacy",
+ valueAttribute: 'account_privacy',
options: [
['all_users', 'Full Profile'],
['private', 'Limited Profile']
@@ -57,7 +55,7 @@ define(['backbone',
var profileImageFieldView = new LearnerProfileFields.ProfileImageFieldView({
model: accountSettingsModel,
- valueAttribute: "profile_image",
+ valueAttribute: 'profile_image',
editable: editable,
messageView: messageView,
imageMaxBytes: Helpers.IMAGE_MAX_BYTES,
@@ -67,9 +65,9 @@ define(['backbone',
});
var usernameFieldView = new FieldViews.ReadonlyFieldView({
- model: accountSettingsModel,
- valueAttribute: "username",
- helpMessage: ""
+ model: accountSettingsModel,
+ valueAttribute: 'username',
+ helpMessage: ''
});
var sectionOneFieldViews = [
@@ -80,7 +78,7 @@ define(['backbone',
showMessages: false,
iconName: 'fa-map-marker',
placeholderValue: '',
- valueAttribute: "country",
+ valueAttribute: 'country',
options: Helpers.FIELD_OPTIONS,
helpMessage: ''
}),
@@ -92,7 +90,7 @@ define(['backbone',
showMessages: false,
iconName: 'fa-comment',
placeholderValue: 'Add language',
- valueAttribute: "language_proficiencies",
+ valueAttribute: 'language_proficiencies',
options: Helpers.FIELD_OPTIONS,
helpMessage: ''
})
@@ -104,9 +102,9 @@ define(['backbone',
editable: editable,
showMessages: false,
title: 'About me',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
"what your interests are, why you're taking courses on edX, or what you hope to learn.",
- valueAttribute: "bio",
+ valueAttribute: 'bio',
helpMessage: '',
messagePosition: 'header'
})
@@ -137,16 +135,15 @@ define(['backbone',
});
};
- beforeEach(function () {
+ beforeEach(function() {
loadFixtures('js/fixtures/student_profile/student_profile.html');
});
- afterEach(function () {
+ afterEach(function() {
Backbone.history.stop();
});
- it("shows loading error correctly", function() {
-
+ it('shows loading error correctly', function() {
var learnerProfileView = createLearnerProfileView(false, 'all_users');
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -158,8 +155,7 @@ define(['backbone',
Helpers.expectLoadingErrorIsVisible(learnerProfileView, true);
});
- it("renders all fields as expected for self with full access", function() {
-
+ it('renders all fields as expected for self with full access', function() {
var learnerProfileView = createLearnerProfileView(true, 'all_users', true);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -171,8 +167,7 @@ define(['backbone',
LearnerProfileHelpers.expectProfileSectionsAndFieldsToBeRendered(learnerProfileView);
});
- it("renders all fields as expected for self with limited access", function() {
-
+ it('renders all fields as expected for self with limited access', function() {
var learnerProfileView = createLearnerProfileView(true, 'private', false);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -184,8 +179,7 @@ define(['backbone',
LearnerProfileHelpers.expectLimitedProfileSectionsAndFieldsToBeRendered(learnerProfileView);
});
- it("renders the fields as expected for others with full access", function() {
-
+ it('renders the fields as expected for others with full access', function() {
var learnerProfileView = createLearnerProfileView(false, 'all_users', true);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -197,8 +191,7 @@ define(['backbone',
LearnerProfileHelpers.expectProfileSectionsAndFieldsToBeRendered(learnerProfileView, true);
});
- it("renders the fields as expected for others with limited access", function() {
-
+ it('renders the fields as expected for others with limited access', function() {
var learnerProfileView = createLearnerProfileView(false, 'private', false);
Helpers.expectLoadingIndicatorIsVisible(learnerProfileView, true);
@@ -210,13 +203,13 @@ define(['backbone',
LearnerProfileHelpers.expectLimitedProfileSectionsAndFieldsToBeRendered(learnerProfileView, true);
});
- it("renders an error if the badges can't be fetched", function () {
+ it("renders an error if the badges can't be fetched", function() {
var learnerProfileView = createLearnerProfileView(false, 'all_users', true);
learnerProfileView.options.accountSettingsModel.set({'accomplishments_shared': true});
var requests = AjaxHelpers.requests(this);
learnerProfileView.render();
-
+
LearnerProfileHelpers.breakBadgeLoading(learnerProfileView, requests);
LearnerProfileHelpers.expectBadgeLoadingErrorIsRendered(learnerProfileView);
});
diff --git a/lms/static/js/spec/student_profile/section_two_tab_spec.js b/lms/static/js/spec/student_profile/section_two_tab_spec.js
index a0236b885a..1180bbc3c4 100644
--- a/lms/static/js/spec/student_profile/section_two_tab_spec.js
+++ b/lms/static/js/spec/student_profile/section_two_tab_spec.js
@@ -4,12 +4,10 @@ define(['backbone', 'jquery', 'underscore',
'js/views/fields',
'js/student_account/models/user_account_model'
],
- function (Backbone, $, _, Helpers, SectionTwoTabView, FieldViews, UserAccountModel) {
- "use strict";
- describe("edx.user.SectionTwoTab", function () {
-
- var createSectionTwoView = function (ownProfile, profileIsPublic) {
-
+ function(Backbone, $, _, Helpers, SectionTwoTabView, FieldViews, UserAccountModel) {
+ 'use strict';
+ describe('edx.user.SectionTwoTab', function() {
+ var createSectionTwoView = function(ownProfile, profileIsPublic) {
var accountSettingsModel = new UserAccountModel();
accountSettingsModel.set(Helpers.createAccountSettingsData());
accountSettingsModel.set({'profile_is_public': profileIsPublic});
@@ -23,9 +21,9 @@ define(['backbone', 'jquery', 'underscore',
editable: editable,
showMessages: false,
title: 'About me',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
"what your interests are, why you're taking courses on edX, or what you hope to learn.",
- valueAttribute: "bio",
+ valueAttribute: 'bio',
helpMessage: '',
messagePosition: 'header'
})
@@ -33,32 +31,32 @@ define(['backbone', 'jquery', 'underscore',
return new SectionTwoTabView({
viewList: sectionTwoFieldViews,
- showFullProfile: function(){
+ showFullProfile: function() {
return profileIsPublic;
},
ownProfile: ownProfile
});
};
- it("full profile displayed for public profile", function () {
+ it('full profile displayed for public profile', function() {
var view = createSectionTwoView(false, true);
view.render();
var bio = view.$el.find('.u-field-bio');
expect(bio.length).toBe(1);
});
-
- it("profile field parts are actually rendered for public profile", function () {
+
+ it('profile field parts are actually rendered for public profile', function() {
var view = createSectionTwoView(false, true);
- _.each(view.options.viewList, function (fieldView) {
- spyOn(fieldView, "render").and.callThrough();
+ _.each(view.options.viewList, function(fieldView) {
+ spyOn(fieldView, 'render').and.callThrough();
});
view.render();
- _.each(view.options.viewList, function (fieldView) {
+ _.each(view.options.viewList, function(fieldView) {
expect(fieldView.render).toHaveBeenCalled();
});
});
- var testPrivateProfile = function (ownProfile, msg_string) {
+ var testPrivateProfile = function(ownProfile, msg_string) {
var view = createSectionTwoView(ownProfile, false);
view.render();
var bio = view.$el.find('.u-field-bio');
@@ -68,45 +66,44 @@ define(['backbone', 'jquery', 'underscore',
expect(_.count(msg.html(), msg_string)).toBeTruthy();
};
- it("no profile when profile is private for other people", function () {
- testPrivateProfile(false, "This learner is currently sharing a limited profile");
+ it('no profile when profile is private for other people', function() {
+ testPrivateProfile(false, 'This learner is currently sharing a limited profile');
});
- it("no profile when profile is private for the user herself", function () {
- testPrivateProfile(true, "You are currently sharing a limited profile");
+ it('no profile when profile is private for the user herself', function() {
+ testPrivateProfile(true, 'You are currently sharing a limited profile');
});
- var testProfilePrivatePartsDoNotRender = function (ownProfile) {
- var view = createSectionTwoView(ownProfile, false);
- _.each(view.options.viewList, function (fieldView) {
- spyOn(fieldView, "render");
+ var testProfilePrivatePartsDoNotRender = function(ownProfile) {
+ var view = createSectionTwoView(ownProfile, false);
+ _.each(view.options.viewList, function(fieldView) {
+ spyOn(fieldView, 'render');
});
view.render();
- _.each(view.options.viewList, function (fieldView) {
+ _.each(view.options.viewList, function(fieldView) {
expect(fieldView.render).not.toHaveBeenCalled();
});
};
- it("profile field parts are not rendered for private profile for owner", function () {
- testProfilePrivatePartsDoNotRender(true);
+ it('profile field parts are not rendered for private profile for owner', function() {
+ testProfilePrivatePartsDoNotRender(true);
});
- it("profile field parts are not rendered for private profile for other people", function () {
- testProfilePrivatePartsDoNotRender(false);
+ it('profile field parts are not rendered for private profile for other people', function() {
+ testProfilePrivatePartsDoNotRender(false);
});
- it("does not allow fields to be edited when visiting a profile for other people", function () {
+ it('does not allow fields to be edited when visiting a profile for other people', function() {
var view = createSectionTwoView(false, true);
var bio = view.options.viewList[0];
- expect(bio.editable).toBe("never");
+ expect(bio.editable).toBe('never');
});
- it("allows fields to be edited when visiting one's own profile", function () {
+ it("allows fields to be edited when visiting one's own profile", function() {
var view = createSectionTwoView(true, true);
var bio = view.options.viewList[0];
- expect(bio.editable).toBe("toggle");
+ expect(bio.editable).toBe('toggle');
});
-
});
}
);
diff --git a/lms/static/js/spec/student_profile/share_modal_view_spec.js b/lms/static/js/spec/student_profile/share_modal_view_spec.js
index a86bfe4916..68e21b8b5e 100644
--- a/lms/static/js/spec/student_profile/share_modal_view_spec.js
+++ b/lms/static/js/spec/student_profile/share_modal_view_spec.js
@@ -4,14 +4,14 @@ define(['backbone', 'jquery', 'underscore', 'moment',
'js/student_profile/views/share_modal_view',
'jquery.simulate'
],
- function (Backbone, $, _, Moment, Helpers, LearnerProfileHelpers, ShareModalView) {
- "use strict";
- describe("edx.user.ShareModalView", function () {
+ function(Backbone, $, _, Moment, Helpers, LearnerProfileHelpers, ShareModalView) {
+ 'use strict';
+ describe('edx.user.ShareModalView', function() {
var keys = $.simulate.keyCode;
var view;
- var createModalView = function () {
+ var createModalView = function() {
var badge = LearnerProfileHelpers.makeBadge(1);
var context = _.extend(badge, {
'created': new Moment(badge.created),
@@ -20,11 +20,11 @@ define(['backbone', 'jquery', 'underscore', 'moment',
});
return new ShareModalView({
model: new Backbone.Model(context),
- shareButton: $("
")
+ shareButton: $('
')
});
};
- beforeEach(function () {
+ beforeEach(function() {
view = createModalView();
// Attach view to document, otherwise click won't work
view.render();
@@ -33,28 +33,27 @@ define(['backbone', 'jquery', 'underscore', 'moment',
expect(view.$el.is(':visible')).toBe(true);
});
- afterEach(function () {
+ afterEach(function() {
view.$el.remove();
});
- it("modal view closes on escape", function () {
- spyOn(view, "close");
+ it('modal view closes on escape', function() {
+ spyOn(view, 'close');
view.delegateEvents();
expect(view.close).not.toHaveBeenCalled();
- $(view.$el).simulate("keydown", {keyCode: keys.ESCAPE});
+ $(view.$el).simulate('keydown', {keyCode: keys.ESCAPE});
expect(view.close).toHaveBeenCalled();
});
- it("modal view closes click on close", function () {
- spyOn(view, "close");
+ it('modal view closes click on close', function() {
+ spyOn(view, 'close');
view.delegateEvents();
- var $closeButton = view.$el.find("button.close");
+ var $closeButton = view.$el.find('button.close');
expect($closeButton.length).toBe(1);
expect(view.close).not.toHaveBeenCalled();
$closeButton.trigger('click');
expect(view.close).toHaveBeenCalled();
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/image_input_spec.js b/lms/static/js/spec/verify_student/image_input_spec.js
index 2d700ef527..0b8b71908c 100644
--- a/lms/static/js/spec/verify_student/image_input_spec.js
+++ b/lms/static/js/spec/verify_student/image_input_spec.js
@@ -5,48 +5,47 @@ define([
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'js/verify_student/views/image_input_view',
'js/verify_student/models/verification_model'
-], function( $, Backbone, TemplateHelpers, AjaxHelpers, ImageInputView, VerificationModel ) {
+], function($, Backbone, TemplateHelpers, AjaxHelpers, ImageInputView, VerificationModel) {
'use strict';
- describe( 'edx.verify_student.ImageInputView', function() {
-
+ describe('edx.verify_student.ImageInputView', function() {
var IMAGE_DATA = 'abcd1234';
var createView = function() {
return new ImageInputView({
- el: $( '#current-step-container' ),
+ el: $('#current-step-container'),
model: new VerificationModel({}),
modelAttribute: 'faceImage',
- errorModel: new ( Backbone.Model.extend({}) )(),
- submitButton: $( '#submit_button' ),
+ errorModel: new (Backbone.Model.extend({}))(),
+ submitButton: $('#submit_button')
}).render();
};
- var uploadImage = function( view, fileType ) {
+ var uploadImage = function(view, fileType) {
var deferred = $.Deferred();
// Since image upload is an asynchronous process,
// we need to wait for the upload to complete
// before checking the outcome.
var fakeFile,
- fakeEvent = { target: { files: [] } };
+ fakeEvent = {target: {files: []}};
// If no file type is specified, don't add any files.
// This simulates what happens when the user clicks
// "cancel" after clicking the input.
- if ( fileType !== null) {
+ if (fileType !== null) {
fakeFile = new Blob(
- [ IMAGE_DATA ],
- { type: 'image/' + fileType }
+ [IMAGE_DATA],
+ {type: 'image/' + fileType}
);
- fakeEvent.target.files = [ fakeFile ];
+ fakeEvent.target.files = [fakeFile];
}
// Wait for either a successful upload or an error
- view.on( 'imageCaptured', function() {
+ view.on('imageCaptured', function() {
deferred.resolve();
});
- view.on( 'error', function() {
+ view.on('error', function() {
deferred.resolve();
});
@@ -54,39 +53,39 @@ define([
// It's impossible to trigger this directly due
// to browser security restrictions, so we call
// the handler instead.
- view.handleInputChange( fakeEvent );
+ view.handleInputChange(fakeEvent);
return deferred.promise();
};
- var expectPreview = function( view, fileType ) {
+ var expectPreview = function(view, fileType) {
var previewImage = view.$preview.attr('src');
- if ( fileType ) {
- expect( previewImage ).toContain( 'data:image/' + fileType );
+ if (fileType) {
+ expect(previewImage).toContain('data:image/' + fileType);
} else {
- expect( previewImage ).toEqual( '' );
+ expect(previewImage).toEqual('');
}
};
- var expectSubmitEnabled = function( isEnabled ) {
- var appearsDisabled = $( '#submit_button' ).hasClass( 'is-disabled' ),
- isDisabled = $( '#submit_button' ).prop( 'disabled' );
+ var expectSubmitEnabled = function(isEnabled) {
+ var appearsDisabled = $('#submit_button').hasClass('is-disabled'),
+ isDisabled = $('#submit_button').prop('disabled');
- expect( !appearsDisabled ).toEqual( isEnabled );
- expect( !isDisabled ).toEqual( isEnabled );
+ expect(!appearsDisabled).toEqual(isEnabled);
+ expect(!isDisabled).toEqual(isEnabled);
};
- var expectImageData = function( view, fileType ) {
- var imageData = view.model.get( view.modelAttribute );
- if ( fileType ) {
- expect( imageData ).toContain( 'data:image/' + fileType );
+ var expectImageData = function(view, fileType) {
+ var imageData = view.model.get(view.modelAttribute);
+ if (fileType) {
+ expect(imageData).toContain('data:image/' + fileType);
} else {
- expect( imageData ).toEqual( '' );
+ expect(imageData).toEqual('');
}
};
- var expectError = function( view ) {
- expect( view.errorModel.get('shown') ).toBe(true);
+ var expectError = function(view) {
+ expect(view.errorModel.get('shown')).toBe(true);
};
beforeEach(function() {
@@ -94,52 +93,52 @@ define([
'
' +
'
'
);
- TemplateHelpers.installTemplate( 'templates/verify_student/image_input' );
+ TemplateHelpers.installTemplate('templates/verify_student/image_input');
});
- it( 'initially disables the submit button', function() {
+ it('initially disables the submit button', function() {
createView();
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
});
- it( 'uploads a png image', function(done) {
+ it('uploads a png image', function(done) {
var view = createView();
- uploadImage( view, 'png').then(function() {
- expectPreview( view, 'png' );
- expectSubmitEnabled( true );
- expectImageData( view, 'png' );
+ uploadImage(view, 'png').then(function() {
+ expectPreview(view, 'png');
+ expectSubmitEnabled(true);
+ expectImageData(view, 'png');
}).always(done);
});
- it( 'uploads a jpeg image', function(done) {
+ it('uploads a jpeg image', function(done) {
var view = createView();
- uploadImage( view, 'jpeg').then(function() {
- expectPreview( view, 'jpeg' );
- expectSubmitEnabled( true );
- expectImageData( view, 'jpeg' );
+ uploadImage(view, 'jpeg').then(function() {
+ expectPreview(view, 'jpeg');
+ expectSubmitEnabled(true);
+ expectImageData(view, 'jpeg');
}).always(done);
});
- it( 'hides the preview when the user cancels the upload', function(done) {
+ it('hides the preview when the user cancels the upload', function(done) {
var view = createView();
- uploadImage( view, null).then(function() {
- expectPreview( view, null );
- expectSubmitEnabled( false );
- expectImageData( view, null );
+ uploadImage(view, null).then(function() {
+ expectPreview(view, null);
+ expectSubmitEnabled(false);
+ expectImageData(view, null);
}).always(done);
});
- it( 'shows an error if the file type is not supported', function(done) {
+ it('shows an error if the file type is not supported', function(done) {
var view = createView();
- uploadImage( view, 'txt').then(function() {
- expectPreview( view, null );
- expectError( view );
- expectSubmitEnabled( false );
- expectImageData( view, null );
+ uploadImage(view, 'txt').then(function() {
+ expectPreview(view, null);
+ expectError(view);
+ expectSubmitEnabled(false);
+ expectImageData(view, null);
}).always(done);
});
});
diff --git a/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js b/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js
index 395b6918e8..fb191e9759 100644
--- a/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js
+++ b/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js
@@ -1,12 +1,12 @@
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'common/js/spec_helpers/template_helpers',
- 'js/verify_student/views/make_payment_step_view'
- ],
- function( $, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView ) {
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/verify_student/views/make_payment_step_view'
+],
+ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) {
'use strict';
var checkPaymentButtons,
@@ -18,8 +18,7 @@ define([
createView,
SERVER_ERROR_MSG = 'An error occurred!';
- describe( 'edx.verify_student.MakePaymentStepView', function() {
-
+ describe('edx.verify_student.MakePaymentStepView', function() {
var STEP_DATA = {
minPrice: '12',
currency: 'usd',
@@ -29,44 +28,44 @@ define([
isABTesting: true
};
- createView = function( stepDataOverrides ) {
+ createView = function(stepDataOverrides) {
var view = new MakePaymentStepView({
- el: $( '#current-step-container' ),
- stepData: _.extend( _.clone( STEP_DATA ), stepDataOverrides ),
- errorModel: new ( Backbone.Model.extend({}) )()
+ el: $('#current-step-container'),
+ stepData: _.extend(_.clone(STEP_DATA), stepDataOverrides),
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
// Stub the payment form submission
- spyOn( view, 'submitForm' ).and.callFake( function() {} );
+ spyOn(view, 'submitForm').and.callFake(function() {});
return view;
};
- expectPriceSelected = function( price ) {
- var sel = $( 'input[name="contribution"]' );
+ expectPriceSelected = function(price) {
+ var sel = $('input[name="contribution"]');
// check that contribution value is same as price given
- expect( sel.length ).toEqual(1);
- expect( sel.val() ).toEqual(price);
+ expect(sel.length).toEqual(1);
+ expect(sel.val()).toEqual(price);
};
- expectPaymentButtonEnabled = function( isEnabled ) {
- var el = $( '.payment-button'),
- appearsDisabled = el.hasClass( 'is-disabled' ),
- isDisabled = el.prop( 'disabled' );
+ expectPaymentButtonEnabled = function(isEnabled) {
+ var el = $('.payment-button'),
+ appearsDisabled = el.hasClass('is-disabled'),
+ isDisabled = el.prop('disabled');
- expect( appearsDisabled ).not.toEqual( isEnabled );
- expect( isDisabled ).not.toEqual( isEnabled );
+ expect(appearsDisabled).not.toEqual(isEnabled);
+ expect(isDisabled).not.toEqual(isEnabled);
};
expectPaymentDisabledBecauseInactive = function() {
- var payButton = $( '.payment-button' );
+ var payButton = $('.payment-button');
// Payment button should be hidden
- expect( payButton.length ).toEqual(0);
+ expect(payButton.length).toEqual(0);
};
- goToPayment = function( requests, kwargs ) {
+ goToPayment = function(requests, kwargs) {
var params = {
contribution: kwargs.amount || '',
course_id: kwargs.courseId || '',
@@ -75,25 +74,25 @@ define([
};
// Click the "go to payment" button
- $( '.payment-button' ).click();
+ $('.payment-button').click();
// Verify that the request was made to the server
AjaxHelpers.expectPostRequest(
- requests, '/verify_student/create_order/', $.param( params )
+ requests, '/verify_student/create_order/', $.param(params)
);
// Simulate the server response
- if ( kwargs.succeeds ) {
+ if (kwargs.succeeds) {
// TODO put fixture responses in the right place
AjaxHelpers.respondWithJson(
requests, {payment_page_url: 'http://payment-page-url/', payment_form_data: {foo: 'bar'}}
);
} else {
- AjaxHelpers.respondWithTextError( requests, 400, SERVER_ERROR_MSG);
+ AjaxHelpers.respondWithTextError(requests, 400, SERVER_ERROR_MSG);
}
};
- expectPaymentSubmitted = function( view, params ) {
+ expectPaymentSubmitted = function(view, params) {
var form;
expect(view.submitForm).toHaveBeenCalled();
@@ -104,22 +103,22 @@ define([
expect(form.attr('action')).toEqual('http://payment-page-url/');
};
- checkPaymentButtons = function( requests, buttons ) {
- var $el = $( '.payment-button' );
+ checkPaymentButtons = function(requests, buttons) {
+ var $el = $('.payment-button');
expect($el.length).toEqual(_.size(buttons));
- _.each(buttons, function( expectedText, expectedId ) {
- var buttonEl = $( '#' + expectedId),
+ _.each(buttons, function(expectedText, expectedId) {
+ var buttonEl = $('#' + expectedId),
request;
buttonEl.removeAttr('disabled');
- expect( buttonEl.length ).toEqual( 1 );
- expect( buttonEl[0] ).toHaveClass( 'payment-button' );
- expect( buttonEl[0] ).toHaveText( expectedText );
- expect( buttonEl[0] ).toHaveClass( 'action-primary-blue' );
+ expect(buttonEl.length).toEqual(1);
+ expect(buttonEl[0]).toHaveClass('payment-button');
+ expect(buttonEl[0]).toHaveText(expectedText);
+ expect(buttonEl[0]).toHaveClass('action-primary-blue');
buttonEl[0].click();
- expect( buttonEl[0] ).toHaveClass( 'is-selected' );
- expectPaymentButtonEnabled( false );
+ expect(buttonEl[0]).toHaveClass('is-selected');
+ expectPaymentButtonEnabled(false);
request = AjaxHelpers.currentRequest(requests);
expect(request.requestBody.split('&')).toContain('processor=' + expectedId);
AjaxHelpers.respondWithJson(requests, {});
@@ -129,82 +128,81 @@ define([
beforeEach(function() {
window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'trackLink']);
- setFixtures( '
' );
- TemplateHelpers.installTemplate( 'templates/verify_student/make_payment_step_ab_testing' );
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/verify_student/make_payment_step_ab_testing');
});
- it( 'A/B Testing: check Initialize method with AB testing enable ', function() {
+ it('A/B Testing: check Initialize method with AB testing enable ', function() {
var view = createView();
- expect( view.templateName ).toEqual('make_payment_step_ab_testing');
- expect( view.btnClass ).toEqual('action-primary-blue');
-
+ expect(view.templateName).toEqual('make_payment_step_ab_testing');
+ expect(view.btnClass).toEqual('action-primary-blue');
});
- it( 'shows users only minimum price', function() {
+ it('shows users only minimum price', function() {
var view = createView(),
requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice );
- expectPaymentButtonEnabled( true );
- goToPayment( requests, {
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it( 'A/B Testing: provides working payment buttons for a single processor', function() {
+ it('A/B Testing: provides working payment buttons for a single processor', function() {
createView({processors: ['cybersource']});
- checkPaymentButtons( AjaxHelpers.requests(this), {cybersource: 'Checkout'});
+ checkPaymentButtons(AjaxHelpers.requests(this), {cybersource: 'Checkout'});
});
- it( 'A/B Testing: provides working payment buttons for multiple processors', function() {
+ it('A/B Testing: provides working payment buttons for multiple processors', function() {
createView({processors: ['cybersource', 'paypal', 'other']});
- checkPaymentButtons( AjaxHelpers.requests(this), {
+ checkPaymentButtons(AjaxHelpers.requests(this), {
cybersource: 'Checkout',
paypal: 'Checkout with PayPal',
other: 'Checkout with other'
});
});
- it( 'A/B Testing: by default minimum price is selected if no suggested prices are given', function() {
+ it('A/B Testing: by default minimum price is selected if no suggested prices are given', function() {
var view = createView(),
- requests = AjaxHelpers.requests( this );
+ requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice);
- expectPaymentButtonEnabled( true );
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it( 'A/B Testing: min price is always selected even if contribution amount is provided', function() {
+ it('A/B Testing: min price is always selected even if contribution amount is provided', function() {
// Pre-select a price NOT in the suggestions
createView({
contributionAmount: '99.99'
});
// Expect that the price is filled in
- expectPriceSelected( STEP_DATA.minPrice );
+ expectPriceSelected(STEP_DATA.minPrice);
});
- it( 'A/B Testing: disables payment for inactive users', function() {
- createView({ isActive: false });
+ it('A/B Testing: disables payment for inactive users', function() {
+ createView({isActive: false});
expectPaymentDisabledBecauseInactive();
});
- it( 'A/B Testing: displays an error if the order could not be created', function() {
- var requests = AjaxHelpers.requests( this ),
+ it('A/B Testing: displays an error if the order could not be created', function() {
+ var requests = AjaxHelpers.requests(this),
view = createView();
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
@@ -212,14 +210,13 @@ define([
});
// Expect that an error is displayed
- expect( view.errorModel.get('shown') ).toBe( true );
- expect( view.errorModel.get('errorTitle') ).toEqual( 'Could not submit order' );
- expect( view.errorModel.get('errorMsg') ).toEqual( SERVER_ERROR_MSG );
+ expect(view.errorModel.get('shown')).toBe(true);
+ expect(view.errorModel.get('errorTitle')).toEqual('Could not submit order');
+ expect(view.errorModel.get('errorMsg')).toEqual(SERVER_ERROR_MSG);
// Expect that the payment button is re-enabled
- expectPaymentButtonEnabled( true );
+ expectPaymentButtonEnabled(true);
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/make_payment_step_view_spec.js b/lms/static/js/spec/verify_student/make_payment_step_view_spec.js
index 85fe93d5ca..aea5720205 100644
--- a/lms/static/js/spec/verify_student/make_payment_step_view_spec.js
+++ b/lms/static/js/spec/verify_student/make_payment_step_view_spec.js
@@ -1,119 +1,118 @@
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'common/js/spec_helpers/template_helpers',
- 'js/verify_student/views/make_payment_step_view'
- ],
- function( $, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView ) {
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/verify_student/views/make_payment_step_view'
+],
+ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) {
'use strict';
- describe( 'edx.verify_student.MakePaymentStepView', function() {
-
+ describe('edx.verify_student.MakePaymentStepView', function() {
var PAYMENT_PARAMS = {
- orderId: "test-order",
- signature: "abcd1234"
+ orderId: 'test-order',
+ signature: 'abcd1234'
};
var STEP_DATA = {
- minPrice: "12",
- currency: "usd",
- processors: ["test-payment-processor"],
- courseKey: "edx/test/test",
+ minPrice: '12',
+ currency: 'usd',
+ processors: ['test-payment-processor'],
+ courseKey: 'edx/test/test',
courseModeSlug: 'verified'
};
- var SERVER_ERROR_MSG = "An error occurred!";
+ var SERVER_ERROR_MSG = 'An error occurred!';
- var createView = function( stepDataOverrides ) {
+ var createView = function(stepDataOverrides) {
var view = new MakePaymentStepView({
- el: $( '#current-step-container' ),
- stepData: _.extend( _.clone( STEP_DATA ), stepDataOverrides ),
- errorModel: new ( Backbone.Model.extend({}) )()
+ el: $('#current-step-container'),
+ stepData: _.extend(_.clone(STEP_DATA), stepDataOverrides),
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
// Stub the payment form submission
- spyOn( view, 'submitForm' ).and.callFake( function() {} );
+ spyOn(view, 'submitForm').and.callFake(function() {});
return view;
};
- var expectPriceSelected = function( price ) {
- var sel = $( 'input[name="contribution"]' );
+ var expectPriceSelected = function(price) {
+ var sel = $('input[name="contribution"]');
// check that contribution value is same as price given
- expect( sel.length ).toEqual(1);
- expect( sel.val() ).toEqual(price);
+ expect(sel.length).toEqual(1);
+ expect(sel.val()).toEqual(price);
};
- var expectPaymentButtonEnabled = function( isEnabled ) {
- var el = $( '.payment-button'),
- appearsDisabled = el.hasClass( 'is-disabled' ),
- isDisabled = el.prop( 'disabled' );
+ var expectPaymentButtonEnabled = function(isEnabled) {
+ var el = $('.payment-button'),
+ appearsDisabled = el.hasClass('is-disabled'),
+ isDisabled = el.prop('disabled');
- expect( !appearsDisabled ).toEqual( isEnabled );
- expect( !isDisabled ).toEqual( isEnabled );
+ expect(!appearsDisabled).toEqual(isEnabled);
+ expect(!isDisabled).toEqual(isEnabled);
};
var expectPaymentDisabledBecauseInactive = function() {
- var payButton = $( '.payment-button' );
+ var payButton = $('.payment-button');
// Payment button should be hidden
- expect( payButton.length ).toEqual(0);
+ expect(payButton.length).toEqual(0);
};
- var goToPayment = function( requests, kwargs ) {
+ var goToPayment = function(requests, kwargs) {
var params = {
- contribution: kwargs.amount || "",
- course_id: kwargs.courseId || "",
- processor: kwargs.processor || "",
- sku: kwargs.sku || ""
+ contribution: kwargs.amount || '',
+ course_id: kwargs.courseId || '',
+ processor: kwargs.processor || '',
+ sku: kwargs.sku || ''
};
// Click the "go to payment" button
- $( '.payment-button' ).click();
+ $('.payment-button').click();
// Verify that the request was made to the server
AjaxHelpers.expectPostRequest(
- requests, "/verify_student/create_order/", $.param( params )
+ requests, '/verify_student/create_order/', $.param(params)
);
// Simulate the server response
- if ( kwargs.succeeds ) {
+ if (kwargs.succeeds) {
// TODO put fixture responses in the right place
- AjaxHelpers.respondWithJson( requests, {payment_page_url: 'http://payment-page-url/', payment_form_data: {foo: 'bar'}} );
+ AjaxHelpers.respondWithJson(requests, {payment_page_url: 'http://payment-page-url/', payment_form_data: {foo: 'bar'}});
} else {
- AjaxHelpers.respondWithTextError( requests, 400, SERVER_ERROR_MSG);
+ AjaxHelpers.respondWithTextError(requests, 400, SERVER_ERROR_MSG);
}
};
- var expectPaymentSubmitted = function( view, params ) {
+ var expectPaymentSubmitted = function(view, params) {
var form;
expect(view.submitForm).toHaveBeenCalled();
form = view.submitForm.calls.mostRecent().args[0];
expect(form.serialize()).toEqual($.param(params));
- expect(form.attr('method')).toEqual("POST");
+ expect(form.attr('method')).toEqual('POST');
expect(form.attr('action')).toEqual('http://payment-page-url/');
};
- var checkPaymentButtons = function( requests, buttons ) {
- var $el = $( '.payment-button' );
+ var checkPaymentButtons = function(requests, buttons) {
+ var $el = $('.payment-button');
expect($el.length).toEqual(_.size(buttons));
- _.each(buttons, function( expectedText, expectedId ) {
- var buttonEl = $( '#' + expectedId),
+ _.each(buttons, function(expectedText, expectedId) {
+ var buttonEl = $('#' + expectedId),
request;
buttonEl.removeAttr('disabled');
- expect( buttonEl.length ).toEqual( 1 );
- expect( buttonEl[0] ).toHaveClass( 'payment-button' );
- expect( buttonEl[0] ).toHaveClass( 'action-primary' );
- expect( buttonEl[0] ).toHaveText( expectedText );
+ expect(buttonEl.length).toEqual(1);
+ expect(buttonEl[0]).toHaveClass('payment-button');
+ expect(buttonEl[0]).toHaveClass('action-primary');
+ expect(buttonEl[0]).toHaveText(expectedText);
buttonEl[0].click();
- expect( buttonEl[0] ).toHaveClass( 'is-selected' );
- expectPaymentButtonEnabled( false );
+ expect(buttonEl[0]).toHaveClass('is-selected');
+ expectPaymentButtonEnabled(false);
request = AjaxHelpers.currentRequest(requests);
expect(request.requestBody.split('&')).toContain('processor=' + expectedId);
AjaxHelpers.respondWithJson(requests, {});
@@ -123,31 +122,31 @@ define([
beforeEach(function() {
window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'trackLink']);
- setFixtures( '
' );
- TemplateHelpers.installTemplate( 'templates/verify_student/make_payment_step' );
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/verify_student/make_payment_step');
});
- it( 'shows users only minimum price', function() {
+ it('shows users only minimum price', function() {
var view = createView({}),
requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice );
- expectPaymentButtonEnabled( true );
- goToPayment( requests, {
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it ('view containing verification msg when verification deadline is set and user is active', function() {
+ it('view containing verification msg when verification deadline is set and user is active', function() {
var verificationDeadlineDateFormat = 'Aug 14, 2016 at 23:59 UTC';
createView({
userEmail: 'test@example.com',
requirements: {
- isVisible:true
+ isVisible: true
},
verificationDeadline: verificationDeadlineDateFormat,
isActive: true
@@ -164,11 +163,11 @@ define([
).toEqual(1);
});
- it ('view containing user email when verification deadline is set and user is not active', function() {
+ it('view containing user email when verification deadline is set and user is not active', function() {
createView({
userEmail: 'test@example.com',
requirements: {
- isVisible:true
+ isVisible: true
},
verificationDeadline: true,
isActive: false
@@ -177,61 +176,61 @@ define([
expect($('p.instruction-info:contains("test@example.com")').length).toEqual(1);
});
- it ('view containing user email', function() {
- createView({userEmail: 'test@example.com', requirements: {isVisible:true}, isActive: false});
+ it('view containing user email', function() {
+ createView({userEmail: 'test@example.com', requirements: {isVisible: true}, isActive: false});
expect($('p.instruction-info:contains("test@example.com")').length).toEqual(1);
});
- it( 'provides working payment buttons for a single processor', function() {
+ it('provides working payment buttons for a single processor', function() {
createView({processors: ['cybersource']});
- checkPaymentButtons( AjaxHelpers.requests(this), {cybersource: "Checkout"});
+ checkPaymentButtons(AjaxHelpers.requests(this), {cybersource: 'Checkout'});
});
- it( 'provides working payment buttons for multiple processors', function() {
+ it('provides working payment buttons for multiple processors', function() {
createView({processors: ['cybersource', 'paypal', 'other']});
- checkPaymentButtons( AjaxHelpers.requests(this), {
- cybersource: "Checkout",
- paypal: "Checkout with PayPal",
- other: "Checkout with other"
+ checkPaymentButtons(AjaxHelpers.requests(this), {
+ cybersource: 'Checkout',
+ paypal: 'Checkout with PayPal',
+ other: 'Checkout with other'
});
});
- it( 'by default minimum price is selected if no suggested prices are given', function() {
+ it('by default minimum price is selected if no suggested prices are given', function() {
var view = createView(),
- requests = AjaxHelpers.requests( this );
+ requests = AjaxHelpers.requests(this);
- expectPriceSelected( STEP_DATA.minPrice);
- expectPaymentButtonEnabled( true );
+ expectPriceSelected(STEP_DATA.minPrice);
+ expectPaymentButtonEnabled(true);
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
succeeds: true
});
- expectPaymentSubmitted( view, {foo: 'bar'} );
+ expectPaymentSubmitted(view, {foo: 'bar'});
});
- it( 'min price is always selected even if contribution amount is provided', function() {
+ it('min price is always selected even if contribution amount is provided', function() {
// Pre-select a price NOT in the suggestions
createView({
contributionAmount: '99.99'
});
// Expect that the price is filled in
- expectPriceSelected( STEP_DATA.minPrice );
+ expectPriceSelected(STEP_DATA.minPrice);
});
- it( 'disables payment for inactive users', function() {
- createView({ isActive: false });
+ it('disables payment for inactive users', function() {
+ createView({isActive: false});
expectPaymentDisabledBecauseInactive();
});
- it( 'displays an error if the order could not be created', function() {
- var requests = AjaxHelpers.requests( this ),
+ it('displays an error if the order could not be created', function() {
+ var requests = AjaxHelpers.requests(this),
view = createView({});
- goToPayment( requests, {
+ goToPayment(requests, {
amount: STEP_DATA.minPrice,
courseId: STEP_DATA.courseKey,
processor: STEP_DATA.processors[0],
@@ -239,15 +238,15 @@ define([
});
// Expect that an error is displayed
- expect( view.errorModel.get('shown') ).toBe( true );
- expect( view.errorModel.get('errorTitle') ).toEqual( 'Could not submit order' );
- expect( view.errorModel.get('errorMsg') ).toEqual( SERVER_ERROR_MSG );
+ expect(view.errorModel.get('shown')).toBe(true);
+ expect(view.errorModel.get('errorTitle')).toEqual('Could not submit order');
+ expect(view.errorModel.get('errorMsg')).toEqual(SERVER_ERROR_MSG);
// Expect that the payment button is re-enabled
- expectPaymentButtonEnabled( true );
+ expectPaymentButtonEnabled(true);
});
- it('displays an error if no payment processors are available', function () {
+ it('displays an error if no payment processors are available', function() {
var view = createView({processors: []});
expect(view.errorModel.get('shown')).toBe(true);
expect(view.errorModel.get('errorTitle')).toEqual(
@@ -257,12 +256,11 @@ define([
'Try the transaction again in a few minutes.'
);
});
- it( 'check Initialize method without AB testing ', function() {
+ it('check Initialize method without AB testing ', function() {
var view = createView();
- expect( view.templateName ).toEqual('make_payment_step');
- expect( view.btnClass ).toEqual('action-primary');
+ expect(view.templateName).toEqual('make_payment_step');
+ expect(view.btnClass).toEqual('action-primary');
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js b/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js
index 53f4b1fd8b..f8861f9e22 100644
--- a/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js
+++ b/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js
@@ -1,9 +1,8 @@
define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/views/pay_and_verify_view'],
- function( $, TemplateHelpers, PayAndVerifyView ) {
+ function($, TemplateHelpers, PayAndVerifyView) {
'use strict';
- describe( 'edx.verify_student.PayAndVerifyView', function() {
-
+ describe('edx.verify_student.PayAndVerifyView', function() {
var TEMPLATES = [
'enrollment_confirmation_step',
'error',
@@ -18,52 +17,52 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
];
var INTRO_STEP = {
- name: "intro-step",
- title: "Intro"
+ name: 'intro-step',
+ title: 'Intro'
};
var DISPLAY_STEPS_FOR_PAYMENT = [
{
- name: "make-payment-step",
- title: "Make Payment"
+ name: 'make-payment-step',
+ title: 'Make Payment'
},
{
- name: "payment-confirmation-step",
- title: "Payment Confirmation"
+ name: 'payment-confirmation-step',
+ title: 'Payment Confirmation'
}
];
var DISPLAY_STEPS_FOR_VERIFICATION = [
{
- name: "face-photo-step",
- title: "Take Face Photo"
+ name: 'face-photo-step',
+ title: 'Take Face Photo'
},
{
- name: "id-photo-step",
- title: "ID Photo"
+ name: 'id-photo-step',
+ title: 'ID Photo'
},
{
- name: "review-photos-step",
- title: "Review Photos"
+ name: 'review-photos-step',
+ title: 'Review Photos'
},
{
- name: "enrollment-confirmation-step",
- title: "Enrollment Confirmation"
+ name: 'enrollment-confirmation-step',
+ title: 'Enrollment Confirmation'
}
];
- var createView = function( displaySteps, currentStep ) {
+ var createView = function(displaySteps, currentStep) {
return new PayAndVerifyView({
displaySteps: displaySteps,
currentStep: currentStep,
- errorModel: new ( Backbone.Model.extend({}) )()
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
};
- var expectStepRendered = function( stepName ) {
+ var expectStepRendered = function(stepName) {
// Expect that the step container div rendered
- expect( $( '.' + stepName ).length > 0 ).toBe( true );
+ expect($('.' + stepName).length > 0).toBe(true);
};
beforeEach(function() {
@@ -71,12 +70,12 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
navigator.getUserMedia = jasmine.createSpy();
setFixtures('
');
- $.each( TEMPLATES, function( index, templateName ) {
- TemplateHelpers.installTemplate('templates/verify_student/' + templateName );
+ $.each(TEMPLATES, function(index, templateName) {
+ TemplateHelpers.installTemplate('templates/verify_student/' + templateName);
});
});
- it( 'renders payment and verification steps', function() {
+ it('renders payment and verification steps', function() {
// Create the view, starting on the first step
var view = createView(
DISPLAY_STEPS_FOR_PAYMENT.concat(DISPLAY_STEPS_FOR_VERIFICATION),
@@ -107,7 +106,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
expectStepRendered('enrollment-confirmation-step');
});
- it( 'renders intro and verification steps', function() {
+ it('renders intro and verification steps', function() {
var view = createView(
[INTRO_STEP].concat(DISPLAY_STEPS_FOR_VERIFICATION),
'intro-step'
@@ -130,7 +129,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
expectStepRendered('enrollment-confirmation-step');
});
- it( 'starts from a later step', function() {
+ it('starts from a later step', function() {
// Start from the payment confirmation step
var view = createView(
DISPLAY_STEPS_FOR_PAYMENT.concat(DISPLAY_STEPS_FOR_VERIFICATION),
@@ -143,10 +142,9 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
// Try moving to the next step
view.nextStep();
expectStepRendered('face-photo-step');
-
});
- it( 'jumps to a particular step', function() {
+ it('jumps to a particular step', function() {
// Start on the review photos step
var view = createView(
DISPLAY_STEPS_FOR_VERIFICATION,
@@ -156,7 +154,6 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
// Jump back to the face photo step
view.goToStep('face-photo-step');
expectStepRendered('face-photo-step');
-
});
});
}
diff --git a/lms/static/js/spec/verify_student/reverify_view_spec.js b/lms/static/js/spec/verify_student/reverify_view_spec.js
index e932ea116f..97edebdc69 100644
--- a/lms/static/js/spec/verify_student/reverify_view_spec.js
+++ b/lms/static/js/spec/verify_student/reverify_view_spec.js
@@ -3,27 +3,26 @@
**/
define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/views/review_photos_step_view',
'js/verify_student/views/reverify_view'],
- function( $, TemplateHelpers, ReviewPhotosStepView, ReverifyView ) {
+ function($, TemplateHelpers, ReviewPhotosStepView, ReverifyView) {
'use strict';
- describe( 'edx.verify_student.ReverifyView', function() {
-
+ describe('edx.verify_student.ReverifyView', function() {
var TEMPLATES = [
- "webcam_photo",
- "image_input",
- "error",
- "face_photo_step",
- "id_photo_step",
- "review_photos_step",
- "reverify_success_step"
+ 'webcam_photo',
+ 'image_input',
+ 'error',
+ 'face_photo_step',
+ 'id_photo_step',
+ 'review_photos_step',
+ 'reverify_success_step'
];
var STEP_INFO = {
'face-photo-step': {
- platformName: 'edX',
+ platformName: 'edX'
},
'id-photo-step': {
- platformName: 'edX',
+ platformName: 'edX'
},
'review-photos-step': {
fullName: 'John Doe',
@@ -38,9 +37,9 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
return new ReverifyView({stepInfo: STEP_INFO}).render();
};
- var expectStepRendered = function( stepName ) {
+ var expectStepRendered = function(stepName) {
// Expect that the step container div rendered
- expect( $( '.' + stepName ).length > 0 ).toBe( true );
+ expect($('.' + stepName).length > 0).toBe(true);
};
@@ -49,12 +48,12 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/
navigator.getUserMedia = jasmine.createSpy();
setFixtures('
');
- $.each( TEMPLATES, function( index, templateName ) {
- TemplateHelpers.installTemplate('templates/verify_student/' + templateName );
+ $.each(TEMPLATES, function(index, templateName) {
+ TemplateHelpers.installTemplate('templates/verify_student/' + templateName);
});
});
- it( 'renders verification steps', function() {
+ it('renders verification steps', function() {
var view = createView();
// Go through the flow, verifying that each step renders
diff --git a/lms/static/js/spec/verify_student/review_photos_step_view_spec.js b/lms/static/js/spec/verify_student/review_photos_step_view_spec.js
index 8b63bf5daf..3b5cf6dfc3 100644
--- a/lms/static/js/spec/verify_student/review_photos_step_view_spec.js
+++ b/lms/static/js/spec/verify_student/review_photos_step_view_spec.js
@@ -1,77 +1,76 @@
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'common/js/spec_helpers/template_helpers',
- 'js/verify_student/views/review_photos_step_view',
- 'js/verify_student/models/verification_model'
- ],
- function( $, _, Backbone, AjaxHelpers, TemplateHelpers, ReviewPhotosStepView, VerificationModel ) {
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'common/js/spec_helpers/template_helpers',
+ 'js/verify_student/views/review_photos_step_view',
+ 'js/verify_student/models/verification_model'
+],
+ function($, _, Backbone, AjaxHelpers, TemplateHelpers, ReviewPhotosStepView, VerificationModel) {
'use strict';
- describe( 'edx.verify_student.ReviewPhotosStepView', function() {
-
+ describe('edx.verify_student.ReviewPhotosStepView', function() {
var STEP_DATA = {},
- FULL_NAME = "Test User",
- FACE_IMAGE = "abcd1234",
- PHOTO_ID_IMAGE = "efgh56789",
- SERVER_ERROR_MSG = "An error occurred!";
+ FULL_NAME = 'Test User',
+ FACE_IMAGE = 'abcd1234',
+ PHOTO_ID_IMAGE = 'efgh56789',
+ SERVER_ERROR_MSG = 'An error occurred!';
var createView = function() {
return new ReviewPhotosStepView({
- el: $( '#current-step-container' ),
+ el: $('#current-step-container'),
stepData: STEP_DATA,
model: new VerificationModel({
faceImage: FACE_IMAGE,
identificationImage: PHOTO_ID_IMAGE
}),
- errorModel: new ( Backbone.Model.extend({}) )()
+ errorModel: new (Backbone.Model.extend({}))()
}).render();
};
- var submitPhotos = function( requests, expectedParams, succeeds ) {
+ var submitPhotos = function(requests, expectedParams, succeeds) {
// Submit the photos
- $( '#next_step_button' ).click();
+ $('#next_step_button').click();
// Expect a request to the server
AjaxHelpers.expectRequest(
- requests, "POST", "/verify_student/submit-photos/",
- $.param( expectedParams )
+ requests, 'POST', '/verify_student/submit-photos/',
+ $.param(expectedParams)
);
// Simulate the server response
- if ( succeeds ) {
- AjaxHelpers.respondWithJson( requests, {url: '/arbitrary-url/'} );
+ if (succeeds) {
+ AjaxHelpers.respondWithJson(requests, {url: '/arbitrary-url/'});
} else {
- AjaxHelpers.respondWithTextError( requests, 400, SERVER_ERROR_MSG );
+ AjaxHelpers.respondWithTextError(requests, 400, SERVER_ERROR_MSG);
}
};
- var setFullName = function( fullName ) {
- $('#new-name').val( fullName );
+ var setFullName = function(fullName) {
+ $('#new-name').val(fullName);
};
- var expectSubmitEnabled = function( isEnabled ) {
- var appearsDisabled = $( '#next_step_button' ).hasClass( 'is-disabled' ),
- isDisabled = $( '#next_step_button' ).prop( 'disabled' );
+ var expectSubmitEnabled = function(isEnabled) {
+ var appearsDisabled = $('#next_step_button').hasClass('is-disabled'),
+ isDisabled = $('#next_step_button').prop('disabled');
- expect( !appearsDisabled ).toBe( isEnabled );
- expect( !isDisabled ).toBe( isEnabled );
+ expect(!appearsDisabled).toBe(isEnabled);
+ expect(!isDisabled).toBe(isEnabled);
};
beforeEach(function() {
window.analytics = jasmine.createSpyObj('analytics', ['track', 'page', 'trackLink']);
- setFixtures( '
' );
- TemplateHelpers.installTemplate( 'templates/verify_student/review_photos_step' );
+ setFixtures('
');
+ TemplateHelpers.installTemplate('templates/verify_student/review_photos_step');
});
- it( 'allows the user to change her full name', function() {
- var requests = AjaxHelpers.requests( this );
+ it('allows the user to change her full name', function() {
+ var requests = AjaxHelpers.requests(this);
createView();
- setFullName( FULL_NAME );
+ setFullName(FULL_NAME);
submitPhotos(
requests,
{
@@ -83,8 +82,8 @@ define([
);
});
- it( 'submits photos for verification', function() {
- var requests = AjaxHelpers.requests( this );
+ it('submits photos for verification', function() {
+ var requests = AjaxHelpers.requests(this);
createView();
submitPhotos(
@@ -98,12 +97,12 @@ define([
// Expect that submission is disabled to prevent
// duplicate submission.
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
});
- it( 'displays an error if photo submission fails', function() {
+ it('displays an error if photo submission fails', function() {
var view = createView(),
- requests = AjaxHelpers.requests( this );
+ requests = AjaxHelpers.requests(this);
submitPhotos(
requests,
@@ -116,14 +115,13 @@ define([
// Expect the submit button is re-enabled to allow
// the user to retry.
- expectSubmitEnabled( true );
+ expectSubmitEnabled(true);
// Expect that an error message is displayed
- expect( view.errorModel.get('shown') ).toBe( true );
- expect( view.errorModel.get('errorTitle') ).toEqual( 'Could not submit photos' );
- expect( view.errorModel.get('errorMsg') ).toEqual( SERVER_ERROR_MSG );
+ expect(view.errorModel.get('shown')).toBe(true);
+ expect(view.errorModel.get('errorTitle')).toEqual('Could not submit photos');
+ expect(view.errorModel.get('errorMsg')).toEqual(SERVER_ERROR_MSG);
});
-
});
}
);
diff --git a/lms/static/js/spec/verify_student/webcam_photo_view_spec.js b/lms/static/js/spec/verify_student/webcam_photo_view_spec.js
index 28b45d7cc3..d32b92e5b2 100644
--- a/lms/static/js/spec/verify_student/webcam_photo_view_spec.js
+++ b/lms/static/js/spec/verify_student/webcam_photo_view_spec.js
@@ -1,19 +1,18 @@
define([
- 'jquery',
- 'backbone',
- 'common/js/spec_helpers/template_helpers',
- 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
- 'js/verify_student/views/webcam_photo_view',
- 'js/verify_student/models/verification_model'
- ],
- function( $, Backbone, TemplateHelpers, AjaxHelpers, WebcamPhotoView, VerificationModel ) {
+ 'jquery',
+ 'backbone',
+ 'common/js/spec_helpers/template_helpers',
+ 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
+ 'js/verify_student/views/webcam_photo_view',
+ 'js/verify_student/models/verification_model'
+],
+ function($, Backbone, TemplateHelpers, AjaxHelpers, WebcamPhotoView, VerificationModel) {
'use strict';
- describe( 'edx.verify_student.WebcamPhotoView', function() {
-
- var IMAGE_DATA = "abcd1234",
- VIDEO_ERROR_TITLE = "video capture error",
- VIDEO_ERROR_MSG = "video error msg";
+ describe('edx.verify_student.WebcamPhotoView', function() {
+ var IMAGE_DATA = 'abcd1234',
+ VIDEO_ERROR_TITLE = 'video capture error',
+ VIDEO_ERROR_MSG = 'video error msg';
/**
* For the purposes of these tests, we stub out the backend
@@ -25,59 +24,58 @@ define([
* cover the HTML5 / Flash webcam integration. We will need
* cross-browser manual testing to verify that this works correctly.
*/
- var StubBackend = function( name, isSupported, snapshotSuccess ) {
-
- if ( _.isUndefined( isSupported ) ) {
+ var StubBackend = function(name, isSupported, snapshotSuccess) {
+ if (_.isUndefined(isSupported)) {
isSupported = true;
}
- if ( _.isUndefined( snapshotSuccess ) ) {
+ if (_.isUndefined(snapshotSuccess)) {
snapshotSuccess = true;
}
return {
name: name,
initialize: function() {},
- isSupported: function() { return isSupported; },
+ isSupported: function() { return isSupported; },
snapshot: function() { return snapshotSuccess; },
getImageData: function() { return IMAGE_DATA; },
reset: function() {}
};
};
- var createView = function( backendStub ) {
+ var createView = function(backendStub) {
return new WebcamPhotoView({
- el: $( '#current-step-container' ),
+ el: $('#current-step-container'),
model: new VerificationModel({}),
modelAttribute: 'faceImage',
- errorModel: new ( Backbone.Model.extend({}) )(),
- submitButton: $( '#submit_button' ),
+ errorModel: new (Backbone.Model.extend({}))(),
+ submitButton: $('#submit_button'),
backend: backendStub
}).render();
};
var takeSnapshot = function() {
- $( '#webcam_capture_button' ).click();
+ $('#webcam_capture_button').click();
};
var resetWebcam = function() {
- $( '#webcam_reset_button' ).click();
+ $('#webcam_reset_button').click();
};
- var expectButtonShown = function( obj ) {
- var resetButton = $( '#webcam_reset_button' ),
- captureButton = $( '#webcam_capture_button' );
+ var expectButtonShown = function(obj) {
+ var resetButton = $('#webcam_reset_button'),
+ captureButton = $('#webcam_capture_button');
- expect( captureButton.hasClass( 'is-hidden') ).toBe( !obj.snapshot );
- expect( resetButton.hasClass( 'is-hidden') ).toBe( !obj.reset );
+ expect(captureButton.hasClass('is-hidden')).toBe(!obj.snapshot);
+ expect(resetButton.hasClass('is-hidden')).toBe(!obj.reset);
};
- var expectSubmitEnabled = function( isEnabled ) {
- var appearsDisabled = $( '#submit_button' ).hasClass( 'is-disabled' ),
- isDisabled = $( '#submit_button' ).prop( 'disabled' );
+ var expectSubmitEnabled = function(isEnabled) {
+ var appearsDisabled = $('#submit_button').hasClass('is-disabled'),
+ isDisabled = $('#submit_button').prop('disabled');
- expect( !appearsDisabled ).toEqual( isEnabled );
- expect( !isDisabled ).toEqual( isEnabled );
+ expect(!appearsDisabled).toEqual(isEnabled);
+ expect(!isDisabled).toEqual(isEnabled);
};
beforeEach(function() {
@@ -87,14 +85,14 @@ define([
'
' +
'
'
);
- TemplateHelpers.installTemplate( 'templates/verify_student/webcam_photo' );
+ TemplateHelpers.installTemplate('templates/verify_student/webcam_photo');
});
- it( 'takes a snapshot', function() {
- var view = createView( new StubBackend( "html5" ) );
+ it('takes a snapshot', function() {
+ var view = createView(new StubBackend('html5'));
// Spy on the backend
- spyOn( view.backend, 'snapshot' ).and.callThrough();
+ spyOn(view.backend, 'snapshot').and.callThrough();
// Initially, only the snapshot button is shown
expectButtonShown({
@@ -102,57 +100,57 @@ define([
reset: false
});
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
// Take the snapshot
takeSnapshot();
// Expect that the backend was used to take the snapshot
- expect( view.backend.snapshot ).toHaveBeenCalled();
+ expect(view.backend.snapshot).toHaveBeenCalled();
// Expect that buttons were updated
expectButtonShown({
snapshot: false,
reset: true
});
- expectSubmitEnabled( true );
+ expectSubmitEnabled(true);
// Expect that the image data was saved to the model
- expect( view.model.get( 'faceImage' ) ).toEqual( IMAGE_DATA );
+ expect(view.model.get('faceImage')).toEqual(IMAGE_DATA);
});
- it( 'resets the camera', function() {
- var view = createView( new StubBackend( "html5" ) );
+ it('resets the camera', function() {
+ var view = createView(new StubBackend('html5'));
// Spy on the backend
- spyOn( view.backend, 'reset' ).and.callThrough();
+ spyOn(view.backend, 'reset').and.callThrough();
// Take the snapshot, then reset
takeSnapshot();
resetWebcam();
// Expect that the backend was reset
- expect( view.backend.reset ).toHaveBeenCalled();
+ expect(view.backend.reset).toHaveBeenCalled();
// Expect that we're back to the initial button shown state
expectButtonShown({
snapshot: true,
reset: false
});
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
// Expect that the image data is wiped from the model
- expect( view.model.get( 'faceImage' ) ).toEqual( "" );
+ expect(view.model.get('faceImage')).toEqual('');
});
- it( 'displays an error if the snapshot fails', function() {
- var view = createView( new StubBackend( "html5", true, false ) );
+ it('displays an error if the snapshot fails', function() {
+ var view = createView(new StubBackend('html5', true, false));
// Take a snapshot
takeSnapshot();
// Do NOT expect an error displayed
- expect( view.errorModel.get( 'shown' ) ).not.toBe( true );
+ expect(view.errorModel.get('shown')).not.toBe(true);
// Expect that the capture button is still enabled
// so the user can retry.
@@ -163,31 +161,29 @@ define([
// Expect that submit is NOT enabled, since the user didn't
// successfully take a snapshot.
- expectSubmitEnabled( false );
+ expectSubmitEnabled(false);
});
- it( 'displays an error triggered by the backend', function() {
- var view = createView( new StubBackend( "html5") );
+ it('displays an error triggered by the backend', function() {
+ var view = createView(new StubBackend('html5'));
// Simulate an error triggered by the backend
// This could occur at any point, including
// while the video capture is being set up.
- view.backend.trigger( 'error', VIDEO_ERROR_TITLE, VIDEO_ERROR_MSG );
+ view.backend.trigger('error', VIDEO_ERROR_TITLE, VIDEO_ERROR_MSG);
// Verify that the error is displayed
- expect( view.errorModel.get( 'errorTitle' ) ).toEqual( VIDEO_ERROR_TITLE );
- expect( view.errorModel.get( 'errorMsg' ) ).toEqual( VIDEO_ERROR_MSG );
- expect( view.errorModel.get( 'shown' ) ).toBe( true );
+ expect(view.errorModel.get('errorTitle')).toEqual(VIDEO_ERROR_TITLE);
+ expect(view.errorModel.get('errorMsg')).toEqual(VIDEO_ERROR_MSG);
+ expect(view.errorModel.get('shown')).toBe(true);
// Expect that buttons are hidden
expectButtonShown({
snapshot: false,
reset: false
});
- expectSubmitEnabled( false );
-
+ expectSubmitEnabled(false);
});
-
});
}
);
diff --git a/lms/static/js/spec/views/fields_helpers.js b/lms/static/js/spec/views/fields_helpers.js
index dad147c248..3d4e6eef21 100644
--- a/lms/static/js/spec/views/fields_helpers.js
+++ b/lms/static/js/spec/views/fields_helpers.js
@@ -1,12 +1,12 @@
define(['backbone',
'jquery',
'underscore',
- 'edx-ui-toolkit/js/utils/html-utils',
+ 'edx-ui-toolkit/js/utils/html-utils',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/template_helpers',
'js/views/fields',
'string_utils'],
- function (Backbone, $, _, HtmlUtils, AjaxHelpers, TemplateHelpers, FieldViews) {
+ function(Backbone, $, _, HtmlUtils, AjaxHelpers, TemplateHelpers, FieldViews) {
'use strict';
var API_URL = '/api/end_point/v1';
@@ -27,7 +27,7 @@ define(['backbone',
url: API_URL
});
- var createFieldData = function (fieldType, fieldData) {
+ var createFieldData = function(fieldType, fieldData) {
var data = {
model: fieldData.model || new UserAccountModel({}),
title: fieldData.title || 'Field Title',
@@ -37,16 +37,16 @@ define(['backbone',
};
switch (fieldType) {
- case FieldViews.DropdownFieldView:
- data['required'] = fieldData.required || false;
- data['options'] = fieldData.options || SELECT_OPTIONS;
- break;
- case FieldViews.LinkFieldView:
- case FieldViews.PasswordFieldView:
- data['linkTitle'] = fieldData.linkTitle || "Link Title";
- data['linkHref'] = fieldData.linkHref || "/path/to/resource";
- data['emailAttribute'] = 'email';
- break;
+ case FieldViews.DropdownFieldView:
+ data['required'] = fieldData.required || false;
+ data['options'] = fieldData.options || SELECT_OPTIONS;
+ break;
+ case FieldViews.LinkFieldView:
+ case FieldViews.PasswordFieldView:
+ data['linkTitle'] = fieldData.linkTitle || 'Link Title';
+ data['linkHref'] = fieldData.linkHref || '/path/to/resource';
+ data['emailAttribute'] = 'email';
+ break;
}
_.extend(data, fieldData);
@@ -57,10 +57,10 @@ define(['backbone',
var createErrorMessage = function(attribute, user_message) {
var field_errors = {};
field_errors[attribute] = {
- "user_message": user_message
+ 'user_message': user_message
};
return {
- "field_errors": field_errors
+ 'field_errors': field_errors
};
};
@@ -87,8 +87,7 @@ define(['backbone',
);
};
- var verifyMessageUpdates = function (view, data, timerCallback) {
-
+ var verifyMessageUpdates = function(view, data, timerCallback) {
var message = 'Here to help!';
view.showHelpMessage(message);
@@ -118,7 +117,7 @@ define(['backbone',
expectMessageContains(view, view.indicators.error);
};
- var verifySuccessMessageReset = function (view) {
+ var verifySuccessMessageReset = function(view) {
view.showHelpMessage();
expectMessageContains(view, view.helpMessage);
view.showSuccessMessage();
@@ -130,12 +129,12 @@ define(['backbone',
view.showSuccessMessage();
expectMessageContains(view, view.indicators.success);
// But if we change the message, it should not get reset.
- view.showHelpMessage("Do not reset this!");
+ view.showHelpMessage('Do not reset this!');
jasmine.clock().tick(7000);
- expectMessageContains(view, "Do not reset this!");
+ expectMessageContains(view, 'Do not reset this!');
};
- var verifyPersistence = function (fieldClass, requests) {
+ var verifyPersistence = function(fieldClass, requests) {
var fieldData = createFieldData(fieldClass, {
title: 'Username',
valueAttribute: 'username',
@@ -148,16 +147,16 @@ define(['backbone',
var valueInputSelector;
switch (fieldClass) {
- case FieldViews.TextFieldView:
- valueInputSelector = '.u-field-value > input';
- break;
- case FieldViews.DropdownFieldView:
- valueInputSelector = '.u-field-value > select';
- _.extend(fieldData, {validValue: SELECT_OPTIONS[0][0]});
- break;
- case FieldViews.TextareaFieldView:
- valueInputSelector = '.u-field-value > textarea';
- break;
+ case FieldViews.TextFieldView:
+ valueInputSelector = '.u-field-value > input';
+ break;
+ case FieldViews.DropdownFieldView:
+ valueInputSelector = '.u-field-value > select';
+ _.extend(fieldData, {validValue: SELECT_OPTIONS[0][0]});
+ break;
+ case FieldViews.TextareaFieldView:
+ valueInputSelector = '.u-field-value > textarea';
+ break;
}
view.$(valueInputSelector).val(fieldData.validValue).change();
@@ -166,7 +165,7 @@ define(['backbone',
AjaxHelpers.expectNoRequests(requests);
};
- var verifyEditableField = function (view, data, requests) {
+ var verifyEditableField = function(view, data, requests) {
var request_data = {};
var url = view.model.url;
@@ -241,19 +240,19 @@ define(['backbone',
}
};
- var verifyTextField = function (view, data, requests) {
+ var verifyTextField = function(view, data, requests) {
verifyEditableField(view, _.extend({
- valueSelector: '.u-field-value',
- valueInputSelector: '.u-field-value > input'
- }, data),
+ valueSelector: '.u-field-value',
+ valueInputSelector: '.u-field-value > input'
+ }, data),
requests);
};
- var verifyDropDownField = function (view, data, requests) {
+ var verifyDropDownField = function(view, data, requests) {
verifyEditableField(view, _.extend({
- valueSelector: '.u-field-value',
- valueInputSelector: '.u-field-value > select'
- }, data
+ valueSelector: '.u-field-value',
+ valueInputSelector: '.u-field-value > select'
+ }, data
), requests);
};
diff --git a/lms/static/js/spec/views/fields_spec.js b/lms/static/js/spec/views/fields_spec.js
index ce8c2291c0..f574d4c60f 100644
--- a/lms/static/js/spec/views/fields_spec.js
+++ b/lms/static/js/spec/views/fields_spec.js
@@ -1,14 +1,13 @@
define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/template_helpers', 'js/views/fields', 'js/spec/views/fields_helpers',
'string_utils'],
- function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers) {
+ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpecHelpers) {
'use strict';
var USERNAME = 'Legolas',
BIO = "My Name is Theon Greyjoy. I'm member of House Greyjoy";
- describe("edx.FieldViews", function () {
-
+ describe('edx.FieldViews', function() {
var requests,
timerCallback,
dropdownSelectClass = '.u-field-value > select',
@@ -23,7 +22,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
FieldViews.TextareaFieldView
];
- beforeEach(function () {
+ beforeEach(function() {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.clock().install();
});
@@ -32,10 +31,8 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
jasmine.clock().uninstall();
});
- it("updates messages correctly for all fields", function() {
-
+ it('updates messages correctly for all fields', function() {
for (var i = 0; i < fieldViewClasses.length; i++) {
-
var fieldViewClass = fieldViewClasses[i];
var fieldData = FieldViewsSpecHelpers.createFieldData(fieldViewClass, {
title: 'Username',
@@ -48,8 +45,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
}
});
- it("resets to help message some time after success message is set", function() {
-
+ it('resets to help message some time after success message is set', function() {
for (var i = 0; i < fieldViewClasses.length; i++) {
var fieldViewClass = fieldViewClasses[i];
var fieldData = FieldViewsSpecHelpers.createFieldData(fieldViewClass, {
@@ -63,8 +59,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
}
});
- it("sends a PATCH request when saveAttributes is called", function() {
-
+ it('sends a PATCH request when saveAttributes is called', function() {
requests = AjaxHelpers.requests(this);
var fieldViewClass = FieldViews.EditableFieldView;
@@ -88,7 +83,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(request.requestBody).toBe('{"language":"ur"}');
});
- it("correctly renders and updates ReadonlyFieldView", function() {
+ it('correctly renders and updates ReadonlyFieldView', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.ReadonlyFieldView, {
title: 'Username',
valueAttribute: 'username',
@@ -103,8 +98,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.fieldValue()).toBe('bookworm');
});
- it("correctly renders, updates and persists changes to TextFieldView when editable == always", function() {
-
+ it('correctly renders, updates and persists changes to TextFieldView when editable == always', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.TextFieldView, {
@@ -122,13 +116,12 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
validValue: 'My Name',
invalidValue1: 'Your Name',
invalidValue2: 'Her Name',
- validationError: "Think again!",
+ validationError: 'Think again!',
defaultValue: ''
}, requests);
});
- it("correctly renders and updates DropdownFieldView when editable == never", function() {
-
+ it('correctly renders and updates DropdownFieldView when editable == never', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.DropdownFieldView, {
@@ -166,8 +159,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$(dropdownButtonClass).length).toBe(0);
});
- it("correctly renders, updates and persists changes to DropdownFieldView when editable == always", function() {
-
+ it('correctly renders, updates and persists changes to DropdownFieldView when editable == always', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.DropdownFieldView, {
@@ -185,13 +177,12 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
validValue: FieldViewsSpecHelpers.SELECT_OPTIONS[0][0],
invalidValue1: FieldViewsSpecHelpers.SELECT_OPTIONS[1][0],
invalidValue2: FieldViewsSpecHelpers.SELECT_OPTIONS[2][0],
- validationError: "Nope, this will not do!",
+ validationError: 'Nope, this will not do!',
defaultValue: null
}, requests);
});
- it("correctly renders, updates and persists changes to DropdownFieldView when editable == toggle", function() {
-
+ it('correctly renders, updates and persists changes to DropdownFieldView when editable == toggle', function() {
requests = AjaxHelpers.requests(this);
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.DropdownFieldView, {
@@ -211,12 +202,12 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
validValue: FieldViewsSpecHelpers.SELECT_OPTIONS[0][0],
invalidValue1: FieldViewsSpecHelpers.SELECT_OPTIONS[1][0],
invalidValue2: FieldViewsSpecHelpers.SELECT_OPTIONS[2][0],
- validationError: "Nope, this will not do!",
+ validationError: 'Nope, this will not do!',
defaultValue: null
}, requests);
});
- it("only shows empty option in DropdownFieldView if required is false or model value is not set", function() {
+ it('only shows empty option in DropdownFieldView if required is false or model value is not set', function() {
requests = AjaxHelpers.requests(this);
var editableOptions = ['toggle', 'always'];
@@ -226,7 +217,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
valueAttribute: 'drop-down',
helpMessage: 'edX drop down',
editable: editable,
- required:true,
+ required: true,
persistChanges: true
});
var view = new FieldViews.DropdownFieldView(fieldData).render();
@@ -249,13 +240,13 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
});
});
- it("correctly renders and updates TextAreaFieldView when editable == never", function() {
+ it('correctly renders and updates TextAreaFieldView when editable == never', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.TextareaFieldView, {
title: 'About me',
valueAttribute: 'bio',
helpMessage: 'Wicked is good',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
- "what your interests are, why you’re taking courses on edX, or what you hope to learn.",
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
+ 'what your interests are, why you’re taking courses on edX, or what you hope to learn.',
editable: 'never',
persistChanges: true,
messagePosition: 'header'
@@ -278,8 +269,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$(textareaLinkClass).length).toBe(0);
});
- it("correctly renders, updates and persists changes to TextAreaFieldView when editable == toggle", function() {
-
+ it('correctly renders, updates and persists changes to TextAreaFieldView when editable == toggle', function() {
requests = AjaxHelpers.requests(this);
var valueInputSelector = '.u-field-value > textarea';
@@ -287,8 +277,8 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
title: 'About me',
valueAttribute: 'bio',
helpMessage: 'Wicked is good',
- placeholderValue: "Tell other edX learners a little about yourself: where you live, " +
- "what your interests are, why you’re taking courses on edX, or what you hope to learn.",
+ placeholderValue: 'Tell other edX learners a little about yourself: where you live, ' +
+ 'what your interests are, why you’re taking courses on edX, or what you hope to learn.',
editable: 'toggle',
persistChanges: true,
messagePosition: 'header'
@@ -322,7 +312,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.fieldValue()).toBe(fieldData.placeholderValue);
});
- it("correctly renders LinkFieldView", function() {
+ it('correctly renders LinkFieldView', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.LinkFieldView, {
title: 'Title',
linkTitle: 'Link title',
@@ -335,7 +325,7 @@ define(['backbone', 'jquery', 'underscore', 'edx-ui-toolkit/js/utils/spec-helper
expect(view.$('.u-field-value > a .u-field-link-title-' + view.options.valueAttribute).text().trim()).toBe(fieldData.linkTitle);
});
- it("correctly renders LinkFieldView", function() {
+ it('correctly renders LinkFieldView', function() {
var fieldData = FieldViewsSpecHelpers.createFieldData(FieldViews.LinkFieldView, {
title: 'Title',
linkTitle: 'Link title',
diff --git a/lms/static/js/spec/views/file_uploader_spec.js b/lms/static/js/spec/views/file_uploader_spec.js
index c530163583..14203e9717 100644
--- a/lms/static/js/spec/views/file_uploader_spec.js
+++ b/lms/static/js/spec/views/file_uploader_spec.js
@@ -1,24 +1,24 @@
define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/template_helpers',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/models/notification', 'string_utils'],
- function (Backbone, $, FileUploaderView, TemplateHelpers, AjaxHelpers, NotificationModel) {
- describe("FileUploaderView", function () {
+ function(Backbone, $, FileUploaderView, TemplateHelpers, AjaxHelpers, NotificationModel) {
+ describe('FileUploaderView', function() {
var verifyTitle, verifyInputLabel, verifyInputTip, verifySubmitButton, verifyExtensions, verifyText,
verifyFileUploadOption, verifyNotificationMessage, verifySubmitButtonEnabled, mimicUpload,
- respondWithSuccess, respondWithError, fileUploaderView, url="http://test_url/";
+ respondWithSuccess, respondWithError, fileUploaderView, url = 'http://test_url/';
- verifyText = function (css, expectedText) {
+ verifyText = function(css, expectedText) {
expect(fileUploaderView.$(css).text().trim()).toBe(expectedText);
};
- verifyTitle = function (expectedTitle) { verifyText('.form-title', expectedTitle); };
+ verifyTitle = function(expectedTitle) { verifyText('.form-title', expectedTitle); };
- verifyInputLabel = function (expectedLabel) { verifyText('.field-label', expectedLabel); };
+ verifyInputLabel = function(expectedLabel) { verifyText('.field-label', expectedLabel); };
- verifyInputTip = function (expectedTip) { verifyText('.tip', expectedTip); };
+ verifyInputTip = function(expectedTip) { verifyText('.tip', expectedTip); };
- verifySubmitButton = function (expectedButton) { verifyText('.submit-file-button', expectedButton); };
+ verifySubmitButton = function(expectedButton) { verifyText('.submit-file-button', expectedButton); };
- verifyExtensions = function (expectedExtensions) {
+ verifyExtensions = function(expectedExtensions) {
var acceptAttribute = fileUploaderView.$('input.input-file').attr('accept');
if (expectedExtensions) {
expect(acceptAttribute).toBe(expectedExtensions);
@@ -28,25 +28,25 @@ define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/
}
};
- verifySubmitButtonEnabled = function (expectedEnabled) {
+ verifySubmitButtonEnabled = function(expectedEnabled) {
var submitButton = fileUploaderView.$('.submit-file-button');
if (expectedEnabled) {
- expect(submitButton).not.toHaveClass("is-disabled");
+ expect(submitButton).not.toHaveClass('is-disabled');
}
else {
- expect(submitButton).toHaveClass("is-disabled");
+ expect(submitButton).toHaveClass('is-disabled');
}
};
- verifyFileUploadOption = function (option, expectedValue) {
+ verifyFileUploadOption = function(option, expectedValue) {
expect(fileUploaderView.$('#file-upload-form').fileupload('option', option)).toBe(expectedValue);
};
- verifyNotificationMessage = function (expectedMessage, type) {
+ verifyNotificationMessage = function(expectedMessage, type) {
verifyText('.file-upload-form-result .message-' + type + ' .message-title', expectedMessage);
};
- mimicUpload = function (test) {
+ mimicUpload = function(test) {
var requests = AjaxHelpers.requests(test);
var param = {files: [{name: 'upload_file.txt'}]};
@@ -59,11 +59,11 @@ define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/
return requests;
};
- respondWithSuccess = function (requests) {
+ respondWithSuccess = function(requests) {
AjaxHelpers.respondWithJson(requests, {});
};
- respondWithError = function (requests, errorMessage) {
+ respondWithError = function(requests, errorMessage) {
if (errorMessage) {
AjaxHelpers.respondWithError(requests, 500, {error: errorMessage});
}
@@ -72,98 +72,98 @@ define(['backbone', 'jquery', 'js/views/file_uploader', 'common/js/spec_helpers/
}
};
- beforeEach(function () {
- setFixtures("
");
+ beforeEach(function() {
+ setFixtures('
');
TemplateHelpers.installTemplate('templates/file-upload');
TemplateHelpers.installTemplate('templates/instructor/instructor_dashboard_2/notification');
fileUploaderView = new FileUploaderView({url: url}).render();
});
- it('has default values', function () {
- verifyTitle("");
- verifyInputLabel("");
- verifyInputTip("");
- verifySubmitButton("Upload File");
+ it('has default values', function() {
+ verifyTitle('');
+ verifyInputLabel('');
+ verifyInputTip('');
+ verifySubmitButton('Upload File');
verifyExtensions(null);
verifySubmitButtonEnabled(false);
});
- it ('can set text values and extensions', function () {
+ it('can set text values and extensions', function() {
fileUploaderView = new FileUploaderView({
- title: "file upload title",
- inputLabel: "test label",
- inputTip: "test tip",
- submitButtonText: "upload button text",
- extensions: ".csv,.txt"
+ title: 'file upload title',
+ inputLabel: 'test label',
+ inputTip: 'test tip',
+ submitButtonText: 'upload button text',
+ extensions: '.csv,.txt'
}).render();
- verifyTitle("file upload title");
- verifyInputLabel("test label");
- verifyInputTip("test tip");
- verifySubmitButton("upload button text");
- verifyExtensions(".csv,.txt");
+ verifyTitle('file upload title');
+ verifyInputLabel('test label');
+ verifyInputTip('test tip');
+ verifySubmitButton('upload button text');
+ verifyExtensions('.csv,.txt');
});
- it ('can store upload URL', function () {
+ it('can store upload URL', function() {
expect(fileUploaderView.$('#file-upload-form').attr('action')).toBe(url);
});
- it ('sets autoUpload to false', function () {
+ it('sets autoUpload to false', function() {
verifyFileUploadOption('autoUpload', false);
});
- it ('sets replaceFileInput to false', function () {
+ it('sets replaceFileInput to false', function() {
verifyFileUploadOption('replaceFileInput', false);
});
- it ('handles errors with default message', function () {
+ it('handles errors with default message', function() {
var requests = mimicUpload(this);
respondWithError(requests);
- verifyNotificationMessage("Your upload of 'upload_file.txt' failed.", "error");
+ verifyNotificationMessage("Your upload of 'upload_file.txt' failed.", 'error');
});
- it ('handles errors with custom message', function () {
+ it('handles errors with custom message', function() {
fileUploaderView = new FileUploaderView({
url: url,
- errorNotification: function (file, event, data) {
+ errorNotification: function(file, event, data) {
var message = interpolate_text("Custom error for '{file}'", {file: file});
return new NotificationModel({
- type: "customized",
+ type: 'customized',
title: message
});
}
}).render();
var requests = mimicUpload(this);
- respondWithError(requests, "server error");
- verifyNotificationMessage("Custom error for 'upload_file.txt'", "customized");
+ respondWithError(requests, 'server error');
+ verifyNotificationMessage("Custom error for 'upload_file.txt'", 'customized');
});
- it ('handles server error message', function () {
+ it('handles server error message', function() {
var requests = mimicUpload(this);
- respondWithError(requests, "server error");
- verifyNotificationMessage("server error", "error");
+ respondWithError(requests, 'server error');
+ verifyNotificationMessage('server error', 'error');
});
- it ('handles success with default message', function () {
+ it('handles success with default message', function() {
var requests = mimicUpload(this);
respondWithSuccess(requests);
- verifyNotificationMessage("Your upload of 'upload_file.txt' succeeded.", "confirmation");
+ verifyNotificationMessage("Your upload of 'upload_file.txt' succeeded.", 'confirmation');
});
- it ('handles success with custom message', function () {
+ it('handles success with custom message', function() {
fileUploaderView = new FileUploaderView({
url: url,
- successNotification: function (file, event, data) {
+ successNotification: function(file, event, data) {
var message = interpolate_text("Custom success message for '{file}'", {file: file});
return new NotificationModel({
- type: "customized",
+ type: 'customized',
title: message
});
}
}).render();
var requests = mimicUpload(this);
respondWithSuccess(requests);
- verifyNotificationMessage("Custom success message for 'upload_file.txt'", "customized");
+ verifyNotificationMessage("Custom success message for 'upload_file.txt'", 'customized');
});
});
});
diff --git a/lms/static/js/spec/views/message_banner_spec.js b/lms/static/js/spec/views/message_banner_spec.js
index 109902aace..cdbf01bdfe 100644
--- a/lms/static/js/spec/views/message_banner_spec.js
+++ b/lms/static/js/spec/views/message_banner_spec.js
@@ -1,14 +1,13 @@
define(['backbone', 'jquery', 'underscore',
'common/js/spec_helpers/template_helpers', 'js/views/message_banner'
],
- function (Backbone, $, _, TemplateHelpers, MessageBannerView) {
+ function(Backbone, $, _, TemplateHelpers, MessageBannerView) {
'use strict';
- describe("MessageBannerView", function () {
-
- beforeEach(function () {
+ describe('MessageBannerView', function() {
+ beforeEach(function() {
setFixtures('
');
- TemplateHelpers.installTemplate("templates/fields/message_banner");
+ TemplateHelpers.installTemplate('templates/fields/message_banner');
});
it('renders message correctly', function() {
diff --git a/lms/static/js/spec/views/notification_spec.js b/lms/static/js/spec/views/notification_spec.js
index 6c6fe45d10..78838be8df 100644
--- a/lms/static/js/spec/views/notification_spec.js
+++ b/lms/static/js/spec/views/notification_spec.js
@@ -1,9 +1,9 @@
define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification', 'common/js/spec_helpers/template_helpers'],
- function (Backbone, $, NotificationModel, NotificationView, TemplateHelpers) {
- describe("NotificationView", function () {
+ function(Backbone, $, NotificationModel, NotificationView, TemplateHelpers) {
+ describe('NotificationView', function() {
var createNotification, verifyTitle, verifyMessage, verifyDetails, verifyAction, notificationView;
- createNotification = function (modelVals) {
+ createNotification = function(modelVals) {
var notificationModel = new NotificationModel(modelVals);
notificationView = new NotificationView({
model: notificationModel
@@ -12,23 +12,23 @@ define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification',
return notificationView;
};
- verifyTitle = function (expectedTitle) {
+ verifyTitle = function(expectedTitle) {
expect(notificationView.$('.message-title').text().trim()).toBe(expectedTitle);
};
- verifyMessage = function (expectedMessage) {
+ verifyMessage = function(expectedMessage) {
expect(notificationView.$('.message-copy').text().trim()).toBe(expectedMessage);
};
- verifyDetails = function (expectedDetails) {
+ verifyDetails = function(expectedDetails) {
var details = notificationView.$('.summary-item');
expect(details.length).toBe(expectedDetails.length);
- details.each(function (index) {
- expect($(this).text().trim()).toBe(expectedDetails[index]);
+ details.each(function(index) {
+ expect($(this).text().trim()).toBe(expectedDetails[index]);
});
};
- verifyAction = function (expectedActionText) {
+ verifyAction = function(expectedActionText) {
var actionButton = notificationView.$('.action-primary');
if (expectedActionText) {
expect(actionButton.text().trim()).toBe(expectedActionText);
@@ -38,12 +38,12 @@ define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification',
}
};
- beforeEach(function () {
- setFixtures("
");
+ beforeEach(function() {
+ setFixtures('
');
TemplateHelpers.installTemplate('templates/instructor/instructor_dashboard_2/notification');
});
- it('has default values', function () {
+ it('has default values', function() {
createNotification({});
expect(notificationView.$('div.message')).toHaveClass('message-confirmation');
verifyTitle('');
@@ -51,44 +51,44 @@ define(['backbone', 'jquery', 'js/models/notification', 'js/views/notification',
verifyAction(null);
});
- it('can use an error type', function () {
+ it('can use an error type', function() {
createNotification({type: 'error'});
expect(notificationView.$('div.message')).toHaveClass('message-error');
expect(notificationView.$('div.message')).not.toHaveClass('message-confirmation');
});
- it('can specify a title', function () {
+ it('can specify a title', function() {
createNotification({title: 'notification title'});
verifyTitle('notification title');
});
- it('can specify a message', function () {
+ it('can specify a message', function() {
createNotification({message: 'This is a dummy message'});
verifyMessage('This is a dummy message');
});
- it('can specify details', function () {
+ it('can specify details', function() {
var expectedDetails = ['detail 1', 'detail 2'];
createNotification({details: expectedDetails});
verifyDetails(expectedDetails);
});
- it ('shows an action button if text and callback are provided', function () {
- createNotification({actionText: 'action text', actionCallback: function () {}});
+ it('shows an action button if text and callback are provided', function() {
+ createNotification({actionText: 'action text', actionCallback: function() {}});
verifyAction('action text');
});
- it ('shows an action button if only text is provided', function () {
+ it('shows an action button if only text is provided', function() {
createNotification({actionText: 'action text'});
verifyAction('action text');
});
- it ('does not show an action button if text is not provided', function () {
- createNotification({actionCallback: function () {}});
+ it('does not show an action button if text is not provided', function() {
+ createNotification({actionCallback: function() {}});
verifyAction(null);
});
- it ('triggers the callback when the action button is clicked', function () {
+ it('triggers the callback when the action button is clicked', function() {
var actionCallback = jasmine.createSpy('Spy on callback');
var view = createNotification({actionText: 'action text', actionCallback: actionCallback});
notificationView.$('button.action-primary').click();
diff --git a/lms/static/js/split.js b/lms/static/js/split.js
index 50a3bbde07..e6d2714ba3 100644
--- a/lms/static/js/split.js
+++ b/lms/static/js/split.js
@@ -33,30 +33,29 @@
var _split; // instead of split for a less common name; avoid conflict
// Avoid running twice; that would break the `nativeSplit` reference
-_split = _split || function (undef) {
-
+_split = _split || function(undef) {
var nativeSplit = String.prototype.split,
- compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group
+ compliantExecNpcg = /()??/.exec('')[1] === undef, // NPCG: nonparticipating capturing group
self;
- self = function (str, separator, limit) {
+ self = function(str, separator, limit) {
// If `separator` is not a regex, use `nativeSplit`
- if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
+ if (Object.prototype.toString.call(separator) !== '[object RegExp]') {
return nativeSplit.call(str, separator, limit);
}
var output = [],
- flags = (separator.ignoreCase ? "i" : "") +
- (separator.multiline ? "m" : "") +
- (separator.extended ? "x" : "") + // Proposed for ES6
- (separator.sticky ? "y" : ""), // Firefox 3+
+ flags = (separator.ignoreCase ? 'i' : '') +
+ (separator.multiline ? 'm' : '') +
+ (separator.extended ? 'x' : '') + // Proposed for ES6
+ (separator.sticky ? 'y' : ''), // Firefox 3+
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
- separator = new RegExp(separator.source, flags + "g"),
+ separator = new RegExp(separator.source, flags + 'g'),
separator2, match, lastIndex, lastLength;
- str += ""; // Type-convert
+ str += ''; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
- separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
+ separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // Math.pow(2, 32) - 1
@@ -76,7 +75,7 @@ _split = _split || function (undef) {
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
- match[0].replace(separator2, function () {
+ match[0].replace(separator2, function() {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undef) {
match[i] = undef;
@@ -98,8 +97,8 @@ _split = _split || function (undef) {
}
}
if (lastLastIndex === str.length) {
- if (lastLength || !separator.test("")) {
- output.push("");
+ if (lastLength || !separator.test('')) {
+ output.push('');
}
} else {
output.push(str.slice(lastLastIndex));
@@ -108,11 +107,10 @@ _split = _split || function (undef) {
};
// For convenience
- String.prototype.split = function (separator, limit) {
+ String.prototype.split = function(separator, limit) {
return self(this, separator, limit);
};
- return self;
-
+ return self;
}();
diff --git a/lms/static/js/staff_debug_actions.js b/lms/static/js/staff_debug_actions.js
index ef77a416cf..b7ae3705ce 100644
--- a/lms/static/js/staff_debug_actions.js
+++ b/lms/static/js/staff_debug_actions.js
@@ -1,128 +1,125 @@
// Build StaffDebug object
-var StaffDebug = (function (){
-
- get_current_url = function() {
- return window.location.pathname;
- };
-
- get_url = function(action){
- var pathname = this.get_current_url();
- var url = pathname.substr(0,pathname.indexOf('/courseware')) + '/instructor/api/' + action;
- return url;
- };
-
- sanitized_string = function(string) {
- return string.replace(/[.*+?^:${}()|[\]\\]/g, "\\$&");
- };
-
- get_user = function(locname){
- locname = sanitized_string(locname);
- var uname = $('#sd_fu_' + locname).val();
- if (uname===""){
- uname = $('#sd_fu_' + locname).attr('placeholder');
- }
- return uname;
- };
-
- do_idash_action = function(action){
- var pdata = {
- 'problem_to_reset': action.location,
- 'unique_student_identifier': get_user(action.locationName),
- 'delete_module': action.delete_module
+var StaffDebug = (function() {
+ get_current_url = function() {
+ return window.location.pathname;
};
- $.ajax({
- type: "POST",
- url: get_url(action.method),
- data: pdata,
- success: function(data){
- var text = _.template(action.success_msg, {interpolate: /\{(.+?)\}/g})(
+
+ get_url = function(action) {
+ var pathname = this.get_current_url();
+ var url = pathname.substr(0, pathname.indexOf('/courseware')) + '/instructor/api/' + action;
+ return url;
+ };
+
+ sanitized_string = function(string) {
+ return string.replace(/[.*+?^:${}()|[\]\\]/g, '\\$&');
+ };
+
+ get_user = function(locname) {
+ locname = sanitized_string(locname);
+ var uname = $('#sd_fu_' + locname).val();
+ if (uname === '') {
+ uname = $('#sd_fu_' + locname).attr('placeholder');
+ }
+ return uname;
+ };
+
+ do_idash_action = function(action) {
+ var pdata = {
+ 'problem_to_reset': action.location,
+ 'unique_student_identifier': get_user(action.locationName),
+ 'delete_module': action.delete_module
+ };
+ $.ajax({
+ type: 'POST',
+ url: get_url(action.method),
+ data: pdata,
+ success: function(data) {
+ var text = _.template(action.success_msg, {interpolate: /\{(.+?)\}/g})(
{user: data.student}
);
- var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
+ var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
{text: text}
);
- $("#result_"+sanitized_string(action.locationName)).html(html);
- },
- error: function(request, status, error) {
- var response_json;
- try {
- response_json = $.parseJSON(request.responseText);
- } catch(e) {
- response_json = { error: gettext('Unknown Error Occurred.') };
- }
- var text = _.template('{error_msg} {error}', {interpolate: /\{(.+?)\}/g})(
- {
- error_msg: action.error_msg,
- error: response_json.error
+ $('#result_' + sanitized_string(action.locationName)).html(html);
+ },
+ error: function(request, status, error) {
+ var response_json;
+ try {
+ response_json = $.parseJSON(request.responseText);
+ } catch (e) {
+ response_json = {error: gettext('Unknown Error Occurred.')};
}
+ var text = _.template('{error_msg} {error}', {interpolate: /\{(.+?)\}/g})(
+ {
+ error_msg: action.error_msg,
+ error: response_json.error
+ }
);
- var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
+ var html = _.template('
{text}
', {interpolate: /\{(.+?)\}/g})(
{text: text}
);
- $("#result_"+sanitized_string(action.locationName)).html(html);
+ $('#result_' + sanitized_string(action.locationName)).html(html);
+ },
+ dataType: 'json'
+ });
+ };
- },
- dataType: 'json'
- });
- };
+ reset = function(locname, location) {
+ this.do_idash_action({
+ locationName: locname,
+ location: location,
+ method: 'reset_student_attempts',
+ success_msg: gettext('Successfully reset the attempts for user {user}'),
+ error_msg: gettext('Failed to reset attempts.'),
+ delete_module: false
+ });
+ };
- reset = function(locname, location){
- this.do_idash_action({
- locationName: locname,
- location: location,
- method: 'reset_student_attempts',
- success_msg: gettext('Successfully reset the attempts for user {user}'),
- error_msg: gettext('Failed to reset attempts.'),
- delete_module: false
- });
- };
+ sdelete = function(locname, location) {
+ this.do_idash_action({
+ locationName: locname,
+ location: location,
+ method: 'reset_student_attempts',
+ success_msg: gettext('Successfully deleted student state for user {user}'),
+ error_msg: gettext('Failed to delete student state.'),
+ delete_module: true
+ });
+ };
- sdelete = function(locname, location){
- this.do_idash_action({
- locationName: locname,
- location: location,
- method: 'reset_student_attempts',
- success_msg: gettext('Successfully deleted student state for user {user}'),
- error_msg: gettext('Failed to delete student state.'),
- delete_module: true
- });
- };
+ rescore = function(locname, location) {
+ this.do_idash_action({
+ locationName: locname,
+ location: location,
+ method: 'rescore_problem',
+ success_msg: gettext('Successfully rescored problem for user {user}'),
+ error_msg: gettext('Failed to rescore problem.'),
+ delete_module: false
+ });
+ };
- rescore = function(locname, location){
- this.do_idash_action({
- locationName: locname,
- location: location,
- method: 'rescore_problem',
- success_msg: gettext('Successfully rescored problem for user {user}'),
- error_msg: gettext('Failed to rescore problem.'),
- delete_module: false
- });
- };
-
- return {
- reset: reset,
- sdelete: sdelete,
- rescore: rescore,
- do_idash_action: do_idash_action,
- get_current_url: get_current_url,
- get_url: get_url,
- get_user: get_user,
- sanitized_string:sanitized_string
- }; })();
+ return {
+ reset: reset,
+ sdelete: sdelete,
+ rescore: rescore,
+ do_idash_action: do_idash_action,
+ get_current_url: get_current_url,
+ get_url: get_url,
+ get_user: get_user,
+ sanitized_string: sanitized_string
+ }; })();
// Register click handlers
$(document).ready(function() {
-
var $courseContent = $('.course-content');
- $courseContent.on("click", '.staff-debug-reset', function() {
+ $courseContent.on('click', '.staff-debug-reset', function() {
StaffDebug.reset($(this).parent().data('location-name'), $(this).parent().data('location'));
return false;
});
- $courseContent.on("click", '.staff-debug-sdelete', function() {
+ $courseContent.on('click', '.staff-debug-sdelete', function() {
StaffDebug.sdelete($(this).parent().data('location-name'), $(this).parent().data('location'));
return false;
});
- $courseContent.on("click", '.staff-debug-rescore', function() {
+ $courseContent.on('click', '.staff-debug-rescore', function() {
StaffDebug.rescore($(this).parent().data('location-name'), $(this).parent().data('location'));
return false;
});
diff --git a/lms/static/js/sticky_filter.js b/lms/static/js/sticky_filter.js
index 895f024eb2..cb112e17d9 100644
--- a/lms/static/js/sticky_filter.js
+++ b/lms/static/js/sticky_filter.js
@@ -1,14 +1,14 @@
$(function() {
- if ($('.filter nav').length > 0) {
- var offset = $('.filter nav').offset().top;
+ if ($('.filter nav').length > 0) {
+ var offset = $('.filter nav').offset().top;
- $(window).scroll(function() {
- if (offset <= window.pageYOffset) {
- return $('.filter nav').addClass('fixed-top');
- }
- else if (offset >= window.pageYOffset) {
- return $('.filter nav').removeClass('fixed-top');
- }
- });
- }
+ $(window).scroll(function() {
+ if (offset <= window.pageYOffset) {
+ return $('.filter nav').addClass('fixed-top');
+ }
+ else if (offset >= window.pageYOffset) {
+ return $('.filter nav').removeClass('fixed-top');
+ }
+ });
+ }
});
diff --git a/lms/static/js/student_account/account.js b/lms/static/js/student_account/account.js
index e05339663d..89d5c4c759 100644
--- a/lms/static/js/student_account/account.js
+++ b/lms/static/js/student_account/account.js
@@ -44,7 +44,7 @@ var edx = edx || {};
model.trigger('sync');
})
.fail(function() {
- var error = gettext("The data could not be saved.");
+ var error = gettext('The data could not be saved.');
model.trigger('error', error);
});
},
@@ -55,10 +55,10 @@ var edx = edx || {};
if (attrs.email.length < this.EMAIL_MIN_LENGTH ||
attrs.email.length > this.EMAIL_MAX_LENGTH ||
!this.EMAIL_REGEX.test(attrs.email)
- ) { errors.email = gettext("Please enter a valid email address"); }
+ ) { errors.email = gettext('Please enter a valid email address'); }
if (attrs.password.length < this.PASSWORD_MIN_LENGTH || attrs.password.length > this.PASSWORD_MAX_LENGTH) {
- errors.password = gettext("Please enter a valid password");
+ errors.password = gettext('Please enter a valid password');
}
if (!$.isEmptyObject(errors)) {
@@ -125,7 +125,7 @@ var edx = edx || {};
.done(function() {
self.$passwordResetStatus
.addClass('success')
- .text(gettext("Password reset email sent. Follow the link in the email to change your password."));
+ .text(gettext('Password reset email sent. Follow the link in the email to change your password.'));
})
.fail(function() {
self.$passwordResetStatus
@@ -159,25 +159,25 @@ var edx = edx || {};
sync: function() {
this.$requestStatus
.addClass('success')
- .text(gettext("Please check your email to confirm the change"));
+ .text(gettext('Please check your email to confirm the change'));
},
clearStatus: function() {
this.$emailStatus
.removeClass('validation-error')
- .text("");
+ .text('');
this.$passwordStatus
.removeClass('validation-error')
- .text("");
+ .text('');
this.$requestStatus
.removeClass('error')
- .text("");
+ .text('');
this.$passwordResetStatus
.removeClass('error')
- .text("");
+ .text('');
}
});
@@ -188,5 +188,4 @@ var edx = edx || {};
} catch (e) {
// TODO: handle exception
}
-
})(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/student_account/emailoptin.js b/lms/static/js/student_account/emailoptin.js
index 20b6d9b306..df0240f4c5 100644
--- a/lms/static/js/student_account/emailoptin.js
+++ b/lms/static/js/student_account/emailoptin.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'jquery.cookie'], function($) {
-
var EmailOptInInterface = {
urls: {
@@ -18,7 +17,7 @@
* @param {string} courseKey Slash-separated course key.
* @param {string} emailOptIn The preference to opt in or out of organization emails.
*/
- setPreference: function( courseKey, emailOptIn ) {
+ setPreference: function(courseKey, emailOptIn) {
return $.ajax({
url: this.urls.emailOptInUrl,
type: 'POST',
diff --git a/lms/static/js/student_account/enrollment.js b/lms/static/js/student_account/enrollment.js
index ecd668f1ae..596fa3e373 100644
--- a/lms/static/js/student_account/enrollment.js
+++ b/lms/static/js/student_account/enrollment.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'jquery.cookie'], function($) {
-
var EnrollmentInterface = {
urls: {
- baskets: '/api/commerce/v0/baskets/',
+ baskets: '/api/commerce/v0/baskets/'
},
headers: {
@@ -17,7 +16,7 @@
* @param {string} courseKey Slash-separated course key.
* @param {string} redirectUrl The URL to redirect to once enrollment completes.
*/
- enroll: function( courseKey, redirectUrl ) {
+ enroll: function(courseKey, redirectUrl) {
var data_obj = {course_id: courseKey},
data = JSON.stringify(data_obj);
@@ -28,25 +27,25 @@
data: data,
headers: this.headers,
context: this
- }).fail(function( jqXHR ) {
+ }).fail(function(jqXHR) {
var responseData = JSON.parse(jqXHR.responseText);
- if ( jqXHR.status === 403 && responseData.user_message_url ) {
+ if (jqXHR.status === 403 && responseData.user_message_url) {
// Check if we've been blocked from the course
// because of country access rules.
// If so, redirect to a page explaining to the user
// why they were blocked.
- this.redirect( responseData.user_message_url );
+ this.redirect(responseData.user_message_url);
} else {
// Otherwise, redirect the user to the next page.
- if ( redirectUrl ) {
- this.redirect( redirectUrl );
+ if (redirectUrl) {
+ this.redirect(redirectUrl);
}
}
}).done(function() {
// If we successfully enrolled, redirect the user
// to the next page (usually the student dashboard or payment flow)
- if ( redirectUrl ) {
- this.redirect( redirectUrl );
+ if (redirectUrl) {
+ this.redirect(redirectUrl);
}
});
},
diff --git a/lms/static/js/student_account/logistration_factory.js b/lms/static/js/student_account/logistration_factory.js
index 88ec6b1fba..f79ea9994f 100644
--- a/lms/static/js/student_account/logistration_factory.js
+++ b/lms/static/js/student_account/logistration_factory.js
@@ -1,9 +1,9 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'js/student_account/views/AccessView'
- ],
+ 'jquery',
+ 'js/student_account/views/AccessView'
+ ],
function($, AccessView) {
return function(options) {
var $logistrationElement = $('#login-and-registration-container');
diff --git a/lms/static/js/student_account/models/LoginModel.js b/lms/static/js/student_account/models/LoginModel.js
index 6fcce3774d..1d2eb9df6f 100644
--- a/lms/static/js/student_account/models/LoginModel.js
+++ b/lms/static/js/student_account/models/LoginModel.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'jquery',
'backbone',
'jquery.url'
- ], function ($, Backbone) {
-
+ ], function($, Backbone) {
return Backbone.Model.extend({
defaults: {
email: '',
@@ -16,12 +15,12 @@
ajaxType: '',
urlRoot: '',
- initialize: function (attributes, options) {
+ initialize: function(attributes, options) {
this.ajaxType = options.method;
this.urlRoot = options.url;
},
- sync: function (method, model) {
+ sync: function(method, model) {
var headers = {'X-CSRFToken': $.cookie('csrftoken')},
data = {},
analytics,
@@ -44,10 +43,10 @@
type: model.ajaxType,
data: data,
headers: headers,
- success: function () {
+ success: function() {
model.trigger('sync');
},
- error: function (error) {
+ error: function(error) {
model.trigger('error', error);
}
});
diff --git a/lms/static/js/student_account/models/PasswordResetModel.js b/lms/static/js/student_account/models/PasswordResetModel.js
index a6ebf0b97d..2e127be7d9 100644
--- a/lms/static/js/student_account/models/PasswordResetModel.js
+++ b/lms/static/js/student_account/models/PasswordResetModel.js
@@ -1,39 +1,38 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'backbone'],
function($, Backbone) {
+ return Backbone.Model.extend({
+ defaults: {
+ email: ''
+ },
+ ajaxType: '',
+ urlRoot: '',
- return Backbone.Model.extend({
- defaults: {
- email: ''
- },
- ajaxType: '',
- urlRoot: '',
+ initialize: function(attributes, options) {
+ this.ajaxType = options.method;
+ this.urlRoot = options.url;
+ },
- initialize: function( attributes, options ) {
- this.ajaxType = options.method;
- this.urlRoot = options.url;
- },
-
- sync: function( method, model ) {
- var headers = {
- 'X-CSRFToken': $.cookie('csrftoken')
- };
+ sync: function(method, model) {
+ var headers = {
+ 'X-CSRFToken': $.cookie('csrftoken')
+ };
// Only expects an email address.
- $.ajax({
- url: model.urlRoot,
- type: model.ajaxType,
- data: model.attributes,
- headers: headers,
- success: function() {
- model.trigger('sync');
- },
- error: function( error ) {
- model.trigger('error', error);
- }
- });
- }
+ $.ajax({
+ url: model.urlRoot,
+ type: model.ajaxType,
+ data: model.attributes,
+ headers: headers,
+ success: function() {
+ model.trigger('sync');
+ },
+ error: function(error) {
+ model.trigger('error', error);
+ }
+ });
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/models/RegisterModel.js b/lms/static/js/student_account/models/RegisterModel.js
index fa30beb1ef..136f429191 100644
--- a/lms/static/js/student_account/models/RegisterModel.js
+++ b/lms/static/js/student_account/models/RegisterModel.js
@@ -1,56 +1,55 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'backbone', 'jquery.url'],
function($, Backbone) {
+ return Backbone.Model.extend({
+ defaults: {
+ email: '',
+ name: '',
+ username: '',
+ password: '',
+ level_of_education: '',
+ gender: '',
+ year_of_birth: '',
+ mailing_address: '',
+ goals: ''
+ },
+ ajaxType: '',
+ urlRoot: '',
- return Backbone.Model.extend({
- defaults: {
- email: '',
- name: '',
- username: '',
- password: '',
- level_of_education: '',
- gender: '',
- year_of_birth: '',
- mailing_address: '',
- goals: ''
- },
- ajaxType: '',
- urlRoot: '',
+ initialize: function(attributes, options) {
+ this.ajaxType = options.method;
+ this.urlRoot = options.url;
+ },
- initialize: function( attributes, options ) {
- this.ajaxType = options.method;
- this.urlRoot = options.url;
- },
-
- sync: function(method, model) {
- var headers = { 'X-CSRFToken': $.cookie('csrftoken') },
- data = {},
- courseId = $.url( '?course_id' );
+ sync: function(method, model) {
+ var headers = {'X-CSRFToken': $.cookie('csrftoken')},
+ data = {},
+ courseId = $.url('?course_id');
// If there is a course ID in the query string param,
// send that to the server as well so it can be included
// in analytics events.
- if ( courseId ) {
- data.course_id = decodeURIComponent(courseId);
- }
+ if (courseId) {
+ data.course_id = decodeURIComponent(courseId);
+ }
// Include all form fields and analytics info in the data sent to the server
- $.extend( data, model.attributes);
+ $.extend(data, model.attributes);
- $.ajax({
- url: model.urlRoot,
- type: model.ajaxType,
- data: data,
- headers: headers,
- success: function() {
- model.trigger('sync');
- },
- error: function( error ) {
- model.trigger('error', error);
- }
- });
- }
+ $.ajax({
+ url: model.urlRoot,
+ type: model.ajaxType,
+ data: data,
+ headers: headers,
+ success: function() {
+ model.trigger('sync');
+ },
+ error: function(error) {
+ model.trigger('error', error);
+ }
+ });
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/models/user_account_model.js b/lms/static/js/student_account/models/user_account_model.js
index 1bc98aa01c..4f9293b92f 100644
--- a/lms/static/js/student_account/models/user_account_model.js
+++ b/lms/static/js/student_account/models/user_account_model.js
@@ -1,9 +1,8 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'underscore', 'backbone'
- ], function (gettext, _, Backbone) {
-
+ ], function(gettext, _, Backbone) {
var UserAccountModel = Backbone.Model.extend({
idAttribute: 'username',
defaults: {
@@ -13,11 +12,11 @@
password: '',
language: null,
country: null,
- date_joined: "",
+ date_joined: '',
gender: null,
- goals: "",
+ goals: '',
level_of_education: null,
- mailing_address: "",
+ mailing_address: '',
year_of_birth: null,
bio: null,
language_proficiencies: [],
@@ -27,7 +26,7 @@
default_public_account_fields: []
},
- parse : function(response) {
+ parse: function(response) {
if (_.isNull(response) || _.isUndefined(response)) {
return {};
}
@@ -35,28 +34,28 @@
// Currently when a non-staff user A access user B's profile, the only way to tell whether user B's
// profile is public is to check if the api has returned fields other than the default public fields
// specified in settings.ACCOUNT_VISIBILITY_CONFIGURATION.
- var responseKeys = _.filter(_.keys(response), function (key) {
- return key !== 'default_public_account_fields';
+ var responseKeys = _.filter(_.keys(response), function(key) {
+ return key !== 'default_public_account_fields';
});
-
+
var isPublic = _.size(_.difference(responseKeys, response.default_public_account_fields)) > 0;
response.profile_is_public = isPublic;
return response;
},
- hasProfileImage: function () {
+ hasProfileImage: function() {
var profile_image = this.get('profile_image');
return (_.isObject(profile_image) && profile_image.has_image === true);
},
- profileImageUrl: function () {
+ profileImageUrl: function() {
return this.get('profile_image').image_url_large;
},
isAboveMinimumAge: function() {
var yearOfBirth = this.get('year_of_birth');
var isBirthDefined = !(_.isUndefined(yearOfBirth) || _.isNull(yearOfBirth));
- return isBirthDefined && !(this.get("requires_parental_consent"));
+ return isBirthDefined && !(this.get('requires_parental_consent'));
}
});
return UserAccountModel;
diff --git a/lms/static/js/student_account/models/user_preferences_model.js b/lms/static/js/student_account/models/user_preferences_model.js
index af421013b3..212d05ca8e 100644
--- a/lms/static/js/student_account/models/user_preferences_model.js
+++ b/lms/static/js/student_account/models/user_preferences_model.js
@@ -1,9 +1,8 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'underscore', 'backbone'
- ], function (gettext, _, Backbone) {
-
+ ], function(gettext, _, Backbone) {
var UserPreferencesModel = Backbone.Model.extend({
idAttribute: 'account_privacy',
defaults: {
diff --git a/lms/static/js/student_account/password_reset.js b/lms/static/js/student_account/password_reset.js
index 9733909315..e26448b4ae 100644
--- a/lms/static/js/student_account/password_reset.js
+++ b/lms/static/js/student_account/password_reset.js
@@ -4,12 +4,12 @@
$(function() {
'use strict';
// adding js class for styling with accessibility in mind
- $("body").addClass("js");
+ $('body').addClass('js');
// form field label styling on focus
- $("form :input").focus(function() {
- $("label[for='" + this.id + "']").parent().addClass("is-focused");
+ $('form :input').focus(function() {
+ $("label[for='" + this.id + "']").parent().addClass('is-focused');
}).blur(function() {
- $("label").parent().removeClass("is-focused");
+ $('label').parent().removeClass('is-focused');
});
});
diff --git a/lms/static/js/student_account/shoppingcart.js b/lms/static/js/student_account/shoppingcart.js
index 36af44f3ee..8dd218ad66 100644
--- a/lms/static/js/student_account/shoppingcart.js
+++ b/lms/static/js/student_account/shoppingcart.js
@@ -1,14 +1,13 @@
/**
* Use the shopping cart to purchase courses.
*/
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'jquery.cookie'], function($) {
-
var ShoppingCartInterface = {
urls: {
- viewCart: "/shoppingcart/",
- addCourse: "/shoppingcart/add/course/"
+ viewCart: '/shoppingcart/',
+ addCourse: '/shoppingcart/add/course/'
},
headers: {
@@ -19,15 +18,15 @@
* Add a course to a cart, then redirect to the view cart page.
* @param {string} courseId The slash-separated course ID to add to the cart.
*/
- addCourseToCart: function( courseId ) {
+ addCourseToCart: function(courseId) {
$.ajax({
- url: this.urls.addCourse + courseId + "/",
+ url: this.urls.addCourse + courseId + '/',
type: 'POST',
data: {},
headers: this.headers,
context: this
}).always(function() {
- this.redirect( this.urls.viewCart );
+ this.redirect(this.urls.viewCart);
});
},
@@ -35,7 +34,7 @@
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
+ redirect: function(url) {
window.location.href = url;
}
};
diff --git a/lms/static/js/student_account/views/AccessView.js b/lms/static/js/student_account/views/AccessView.js
index b18edaacc9..40ef26aaf7 100644
--- a/lms/static/js/student_account/views/AccessView.js
+++ b/lms/static/js/student_account/views/AccessView.js
@@ -1,242 +1,238 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'utility',
- 'underscore',
- 'underscore.string',
- 'backbone',
- 'js/student_account/models/LoginModel',
- 'js/student_account/models/PasswordResetModel',
- 'js/student_account/models/RegisterModel',
- 'js/student_account/views/LoginView',
- 'js/student_account/views/PasswordResetView',
- 'js/student_account/views/RegisterView',
- 'js/student_account/views/InstitutionLoginView',
- 'js/student_account/views/HintedLoginView',
- 'js/vendor/history'
- ],
+ 'jquery',
+ 'utility',
+ 'underscore',
+ 'underscore.string',
+ 'backbone',
+ 'js/student_account/models/LoginModel',
+ 'js/student_account/models/PasswordResetModel',
+ 'js/student_account/models/RegisterModel',
+ 'js/student_account/views/LoginView',
+ 'js/student_account/views/PasswordResetView',
+ 'js/student_account/views/RegisterView',
+ 'js/student_account/views/InstitutionLoginView',
+ 'js/student_account/views/HintedLoginView',
+ 'js/vendor/history'
+ ],
function($, utility, _, _s, Backbone, LoginModel, PasswordResetModel, RegisterModel, LoginView,
PasswordResetView, RegisterView, InstitutionLoginView, HintedLoginView) {
-
- return Backbone.View.extend({
- tpl: '#access-tpl',
- events: {
- 'click .form-toggle': 'toggleForm'
- },
- subview: {
- login: {},
- register: {},
- passwordHelp: {},
- institutionLogin: {},
- hintedLogin: {}
- },
- nextUrl: '/dashboard',
+ return Backbone.View.extend({
+ tpl: '#access-tpl',
+ events: {
+ 'click .form-toggle': 'toggleForm'
+ },
+ subview: {
+ login: {},
+ register: {},
+ passwordHelp: {},
+ institutionLogin: {},
+ hintedLogin: {}
+ },
+ nextUrl: '/dashboard',
// The form currently loaded
- activeForm: '',
-
- initialize: function( options ) {
+ activeForm: '',
+ initialize: function(options) {
/* Mix non-conflicting functions from underscore.string
* (all but include, contains, and reverse) into the
* Underscore namespace
*/
- _.mixin( _s.exports() );
+ _.mixin(_s.exports());
- this.tpl = $(this.tpl).html();
+ this.tpl = $(this.tpl).html();
- this.activeForm = options.initial_mode || 'login';
+ this.activeForm = options.initial_mode || 'login';
- this.thirdPartyAuth = options.third_party_auth || {
- currentProvider: null,
- providers: []
- };
+ this.thirdPartyAuth = options.third_party_auth || {
+ currentProvider: null,
+ providers: []
+ };
- this.thirdPartyAuthHint = options.third_party_auth_hint || null;
+ this.thirdPartyAuthHint = options.third_party_auth_hint || null;
- if (options.login_redirect_url) {
+ if (options.login_redirect_url) {
// Ensure that the next URL is internal for security reasons
- if ( ! window.isExternal( options.login_redirect_url ) ) {
- this.nextUrl = options.login_redirect_url;
+ if (! window.isExternal(options.login_redirect_url)) {
+ this.nextUrl = options.login_redirect_url;
+ }
}
- }
- this.formDescriptions = {
- login: options.login_form_desc,
- register: options.registration_form_desc,
- reset: options.password_reset_form_desc,
- institution_login: null,
- hinted_login: null
- };
+ this.formDescriptions = {
+ login: options.login_form_desc,
+ register: options.registration_form_desc,
+ reset: options.password_reset_form_desc,
+ institution_login: null,
+ hinted_login: null
+ };
- this.platformName = options.platform_name;
- this.supportURL = options.support_link;
+ this.platformName = options.platform_name;
+ this.supportURL = options.support_link;
// The login view listens for 'sync' events from the reset model
- this.resetModel = new PasswordResetModel({}, {
- method: 'GET',
- url: '#'
- });
+ this.resetModel = new PasswordResetModel({}, {
+ method: 'GET',
+ url: '#'
+ });
- this.render();
+ this.render();
// Once the third party error message has been shown once,
// there is no need to show it again, if the user changes mode:
- this.thirdPartyAuth.errorMessage = null;
- },
+ this.thirdPartyAuth.errorMessage = null;
+ },
- render: function() {
- $(this.el).html( _.template(this.tpl)({
- mode: this.activeForm
- }));
+ render: function() {
+ $(this.el).html(_.template(this.tpl)({
+ mode: this.activeForm
+ }));
- this.postRender();
+ this.postRender();
- return this;
- },
+ return this;
+ },
- postRender: function() {
- //get & check current url hash part & load form accordingly
- if (Backbone.history.getHash() === 'forgot-password-modal') {
- this.resetPassword();
- }
- this.loadForm(this.activeForm);
+ postRender: function() {
+ // get & check current url hash part & load form accordingly
+ if (Backbone.history.getHash() === 'forgot-password-modal') {
+ this.resetPassword();
+ }
+ this.loadForm(this.activeForm);
+ },
- },
+ loadForm: function(type) {
+ var loadFunc = _.bind(this.load[type], this);
+ loadFunc(this.formDescriptions[type]);
+ },
- loadForm: function( type ) {
- var loadFunc = _.bind( this.load[type], this );
- loadFunc( this.formDescriptions[type] );
- },
+ load: {
+ login: function(data) {
+ var model = new LoginModel({}, {
+ method: data.method,
+ url: data.submit_url
+ });
- load: {
- login: function( data ) {
- var model = new LoginModel({}, {
- method: data.method,
- url: data.submit_url
- });
-
- this.subview.login = new LoginView({
- fields: data.fields,
- model: model,
- resetModel: this.resetModel,
- thirdPartyAuth: this.thirdPartyAuth,
- platformName: this.platformName,
- supportURL: this.supportURL
- });
+ this.subview.login = new LoginView({
+ fields: data.fields,
+ model: model,
+ resetModel: this.resetModel,
+ thirdPartyAuth: this.thirdPartyAuth,
+ platformName: this.platformName,
+ supportURL: this.supportURL
+ });
// Listen for 'password-help' event to toggle sub-views
- this.listenTo( this.subview.login, 'password-help', this.resetPassword );
+ this.listenTo(this.subview.login, 'password-help', this.resetPassword);
// Listen for 'auth-complete' event so we can enroll/redirect the user appropriately.
- this.listenTo( this.subview.login, 'auth-complete', this.authComplete );
+ this.listenTo(this.subview.login, 'auth-complete', this.authComplete);
+ },
- },
+ reset: function(data) {
+ this.resetModel.ajaxType = data.method;
+ this.resetModel.urlRoot = data.submit_url;
- reset: function( data ) {
- this.resetModel.ajaxType = data.method;
- this.resetModel.urlRoot = data.submit_url;
-
- this.subview.passwordHelp = new PasswordResetView({
- fields: data.fields,
- model: this.resetModel
- });
+ this.subview.passwordHelp = new PasswordResetView({
+ fields: data.fields,
+ model: this.resetModel
+ });
// Listen for 'password-email-sent' event to toggle sub-views
- this.listenTo( this.subview.passwordHelp, 'password-email-sent', this.passwordEmailSent );
+ this.listenTo(this.subview.passwordHelp, 'password-email-sent', this.passwordEmailSent);
// Focus on the form
- $('.password-reset-form').focus();
- },
+ $('.password-reset-form').focus();
+ },
- register: function( data ) {
- var model = new RegisterModel({}, {
- method: data.method,
- url: data.submit_url
- });
+ register: function(data) {
+ var model = new RegisterModel({}, {
+ method: data.method,
+ url: data.submit_url
+ });
- this.subview.register = new RegisterView({
- fields: data.fields,
- model: model,
- thirdPartyAuth: this.thirdPartyAuth,
- platformName: this.platformName
- });
+ this.subview.register = new RegisterView({
+ fields: data.fields,
+ model: model,
+ thirdPartyAuth: this.thirdPartyAuth,
+ platformName: this.platformName
+ });
// Listen for 'auth-complete' event so we can enroll/redirect the user appropriately.
- this.listenTo( this.subview.register, 'auth-complete', this.authComplete );
+ this.listenTo(this.subview.register, 'auth-complete', this.authComplete);
+ },
+
+ institution_login: function(unused) {
+ this.subview.institutionLogin = new InstitutionLoginView({
+ thirdPartyAuth: this.thirdPartyAuth,
+ platformName: this.platformName,
+ mode: this.activeForm
+ });
+
+ this.subview.institutionLogin.render();
+ },
+
+ hinted_login: function(unused) {
+ this.subview.hintedLogin = new HintedLoginView({
+ thirdPartyAuth: this.thirdPartyAuth,
+ hintedProvider: this.thirdPartyAuthHint,
+ platformName: this.platformName
+ });
+
+ this.subview.hintedLogin.render();
+ }
},
- institution_login: function ( unused ) {
- this.subview.institutionLogin = new InstitutionLoginView({
- thirdPartyAuth: this.thirdPartyAuth,
- platformName: this.platformName,
- mode: this.activeForm
- });
-
- this.subview.institutionLogin.render();
+ passwordEmailSent: function() {
+ var $loginAnchorElement = $('#login-anchor');
+ this.element.hide($(this.el).find('#password-reset-anchor'));
+ this.element.show($loginAnchorElement);
+ this.element.scrollTop($loginAnchorElement);
},
- hinted_login: function ( unused ) {
- this.subview.hintedLogin = new HintedLoginView({
- thirdPartyAuth: this.thirdPartyAuth,
- hintedProvider: this.thirdPartyAuthHint,
- platformName: this.platformName
+ resetPassword: function() {
+ window.analytics.track('edx.bi.password_reset_form.viewed', {
+ category: 'user-engagement'
});
- this.subview.hintedLogin.render();
- }
- },
+ this.element.hide($(this.el).find('#login-anchor'));
+ this.loadForm('reset');
+ this.element.scrollTop($('#password-reset-anchor'));
+ },
- passwordEmailSent: function() {
- var $loginAnchorElement = $('#login-anchor');
- this.element.hide( $(this.el).find('#password-reset-anchor') );
- this.element.show( $loginAnchorElement );
- this.element.scrollTop( $loginAnchorElement );
- },
+ toggleForm: function(e) {
+ var type = $(e.currentTarget).data('type'),
+ $form = $('#' + type + '-form'),
+ $anchor = $('#' + type + '-anchor'),
+ queryParams = url('?'),
+ queryStr = queryParams.length > 0 ? '?' + queryParams : '';
- resetPassword: function() {
- window.analytics.track('edx.bi.password_reset_form.viewed', {
- category: 'user-engagement'
- });
+ e.preventDefault();
- this.element.hide( $(this.el).find('#login-anchor') );
- this.loadForm('reset');
- this.element.scrollTop( $('#password-reset-anchor') );
- },
-
- toggleForm: function( e ) {
- var type = $(e.currentTarget).data('type'),
- $form = $('#' + type + '-form'),
- $anchor = $('#' + type + '-anchor'),
- queryParams = url('?'),
- queryStr = queryParams.length > 0 ? '?' + queryParams : '';
-
- e.preventDefault();
-
- window.analytics.track('edx.bi.' + type + '_form.toggled', {
- category: 'user-engagement'
- });
+ window.analytics.track('edx.bi.' + type + '_form.toggled', {
+ category: 'user-engagement'
+ });
// Load the form. Institution login is always refreshed since it changes based on the previous form.
- if ( !this.form.isLoaded( $form ) || type == 'institution_login') {
- this.loadForm( type );
- }
- this.activeForm = type;
+ if (!this.form.isLoaded($form) || type == 'institution_login') {
+ this.loadForm(type);
+ }
+ this.activeForm = type;
- this.element.hide( $(this.el).find('.submission-success') );
- this.element.hide( $(this.el).find('.form-wrapper') );
- this.element.show( $form );
- this.element.scrollTop( $anchor );
+ this.element.hide($(this.el).find('.submission-success'));
+ this.element.hide($(this.el).find('.form-wrapper'));
+ this.element.show($form);
+ this.element.scrollTop($anchor);
// Update url without reloading page
- if (type != 'institution_login') {
- History.pushState( null, document.title, '/' + type + queryStr );
- }
- analytics.page( 'login_and_registration', type );
+ if (type != 'institution_login') {
+ History.pushState(null, document.title, '/' + type + queryStr);
+ }
+ analytics.page('login_and_registration', type);
// Focus on the form
- $('#' + type).focus();
- },
+ $('#' + type).focus();
+ },
/**
* Once authentication has completed successfully:
@@ -245,48 +241,48 @@
* Otherwise, redirect to the specified next step.
*
*/
- authComplete: function() {
- if (this.thirdPartyAuth && this.thirdPartyAuth.finishAuthUrl) {
- this.redirect(this.thirdPartyAuth.finishAuthUrl);
+ authComplete: function() {
+ if (this.thirdPartyAuth && this.thirdPartyAuth.finishAuthUrl) {
+ this.redirect(this.thirdPartyAuth.finishAuthUrl);
// Note: the third party auth URL likely contains another redirect URL embedded inside
- } else {
- this.redirect(this.nextUrl);
- }
- },
+ } else {
+ this.redirect(this.nextUrl);
+ }
+ },
/**
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
- window.location.replace(url);
- },
+ redirect: function(url) {
+ window.location.replace(url);
+ },
- form: {
- isLoaded: function( $form ) {
- return $form.html().length > 0;
- }
- },
+ form: {
+ isLoaded: function($form) {
+ return $form.html().length > 0;
+ }
+ },
/* Helper method to toggle display
* including accessibility considerations
*/
- element: {
- hide: function( $el ) {
- $el.addClass('hidden');
- },
+ element: {
+ hide: function($el) {
+ $el.addClass('hidden');
+ },
- scrollTop: function( $el ) {
+ scrollTop: function($el) {
// Scroll to top of selected element
- $('html,body').animate({
- scrollTop: $el.offset().top
- },'slow');
- },
+ $('html,body').animate({
+ scrollTop: $el.offset().top
+ }, 'slow');
+ },
- show: function( $el ) {
- $el.removeClass('hidden');
+ show: function($el) {
+ $el.removeClass('hidden');
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/FinishAuthView.js b/lms/static/js/student_account/views/FinishAuthView.js
index bef5aa4f2b..870c56b615 100644
--- a/lms/static/js/student_account/views/FinishAuthView.js
+++ b/lms/static/js/student_account/views/FinishAuthView.js
@@ -23,7 +23,7 @@
* - The specified 'nextUrl' if safe, or
* - The dashboard
*/
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'jquery',
@@ -33,8 +33,7 @@
'js/student_account/emailoptin',
'js/student_account/enrollment',
'js/student_account/shoppingcart'
- ], function ($, _, Backbone, gettext, emailOptInInterface, enrollmentInterface, shoppingCartInterface) {
-
+ ], function($, _, Backbone, gettext, emailOptInInterface, enrollmentInterface, shoppingCartInterface) {
var FinishAuthView = Backbone.View.extend({
el: '#finish-auth-status',
@@ -45,14 +44,14 @@
trackSelection: '/course_modes/choose/'
},
- initialize: function( obj ) {
+ initialize: function(obj) {
var queryParams = {
- next: $.url( '?next' ),
- enrollmentAction: $.url( '?enrollment_action' ),
- courseId: $.url( '?course_id' ),
- courseMode: $.url( '?course_mode' ),
- emailOptIn: $.url( '?email_opt_in' ),
- purchaseWorkflow: $.url( '?purchase_workflow' )
+ next: $.url('?next'),
+ enrollmentAction: $.url('?enrollment_action'),
+ courseId: $.url('?course_id'),
+ courseMode: $.url('?course_mode'),
+ emailOptIn: $.url('?email_opt_in'),
+ purchaseWorkflow: $.url('?purchase_workflow')
};
for (var key in queryParams) {
if (queryParams[key]) {
@@ -67,7 +66,7 @@
this.purchaseWorkflow = queryParams.purchaseWorkflow;
if (queryParams.next) {
// Ensure that the next URL is internal for security reasons
- if ( ! window.isExternal( queryParams.next ) ) {
+ if (! window.isExternal(queryParams.next)) {
this.nextUrl = queryParams.next;
}
}
@@ -77,8 +76,8 @@
try {
var next = _.bind(this.enrollment, this);
this.checkEmailOptIn(next);
- } catch(err) {
- this.updateTaskDescription(gettext("Error") + ": " + err.message);
+ } catch (err) {
+ this.updateTaskDescription(gettext('Error') + ': ' + err.message);
this.redirect(this.nextUrl);
}
},
@@ -104,8 +103,8 @@
*/
checkEmailOptIn: function(next) {
// Set the email opt in preference. this.emailOptIn is null or "true" or "false"
- if ((this.emailOptIn === "true" || this.emailOptIn === "false") && this.enrollmentAction) {
- this.updateTaskDescription(gettext("Saving your email preference"));
+ if ((this.emailOptIn === 'true' || this.emailOptIn === 'false') && this.enrollmentAction) {
+ this.updateTaskDescription(gettext('Saving your email preference'));
emailOptInInterface
.setPreference(this.courseId, this.emailOptIn)
.always(next);
@@ -122,12 +121,12 @@
enrollment: function() {
var redirectUrl = this.nextUrl;
- if ( this.enrollmentAction === 'enroll' && this.courseId ) {
- this.updateTaskDescription(gettext("Enrolling you in the selected course"));
- var courseId = decodeURIComponent( this.courseId );
+ if (this.enrollmentAction === 'enroll' && this.courseId) {
+ this.updateTaskDescription(gettext('Enrolling you in the selected course'));
+ var courseId = decodeURIComponent(this.courseId);
// Determine where to redirect the user after auto-enrollment.
- if ( !this.courseMode ) {
+ if (!this.courseMode) {
/* Backwards compatibility with the original course details page.
The old implementation did not specify the course mode for enrollment,
so we'd always send the user to the "track selection" page.
@@ -135,7 +134,7 @@
("verified", "honor", etc.) -- or, if the only course mode was "honor",
it would redirect the user to the dashboard. */
redirectUrl = this.appendPurchaseWorkflow(this.urls.trackSelection + courseId + '/');
- } else if ( this.courseMode === 'honor' || this.courseMode === 'audit' ) {
+ } else if (this.courseMode === 'honor' || this.courseMode === 'audit') {
/* The newer version of the course details page allows the user
to specify which course mode to enroll as. If the student has
chosen "honor", we send them immediately to the next URL
@@ -149,17 +148,17 @@
/* Attempt to auto-enroll the user in a free mode of the course,
then redirect to the next location. */
- enrollmentInterface.enroll( courseId, redirectUrl );
- } else if ( this.enrollmentAction === 'add_to_cart' && this.courseId) {
+ enrollmentInterface.enroll(courseId, redirectUrl);
+ } else if (this.enrollmentAction === 'add_to_cart' && this.courseId) {
/*
If this is a paid course, add it to the shopping cart and redirect
the user to the "view cart" page.
*/
- this.updateTaskDescription(gettext("Adding the selected course to your cart"));
- shoppingCartInterface.addCourseToCart( this.courseId );
+ this.updateTaskDescription(gettext('Adding the selected course to your cart'));
+ shoppingCartInterface.addCourseToCart(this.courseId);
} else {
// Otherwise, redirect the user to the next page.
- this.redirect( redirectUrl );
+ this.redirect(redirectUrl);
}
},
@@ -167,8 +166,8 @@
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
- this.updateTaskDescription(gettext("Loading your courses"));
+ redirect: function(url) {
+ this.updateTaskDescription(gettext('Loading your courses'));
window.location.replace(url);
}
});
diff --git a/lms/static/js/student_account/views/FormView.js b/lms/static/js/student_account/views/FormView.js
index 5e98e2bb4b..92dbd73b2c 100644
--- a/lms/static/js/student_account/views/FormView.js
+++ b/lms/static/js/student_account/views/FormView.js
@@ -1,261 +1,259 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'backbone',
- 'common/js/utils/edx.utils.validate'
- ],
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'common/js/utils/edx.utils.validate'
+ ],
function($, _, Backbone, EdxUtilsValidate) {
+ return Backbone.View.extend({
+ tagName: 'form',
- return Backbone.View.extend({
- tagName: 'form',
+ el: '',
- el: '',
+ tpl: '',
- tpl: '',
+ fieldTpl: '#form_field-tpl',
- fieldTpl: '#form_field-tpl',
+ events: {},
- events: {},
+ errors: [],
- errors: [],
+ formType: '',
- formType: '',
+ $form: {},
- $form: {},
-
- fields: [],
+ fields: [],
// String to append to required label fields
- requiredStr: '*',
+ requiredStr: '*',
- submitButton: '',
+ submitButton: '',
- initialize: function( data ) {
- this.model = data.model;
- this.preRender( data );
+ initialize: function(data) {
+ this.model = data.model;
+ this.preRender(data);
- this.tpl = $(this.tpl).html();
- this.fieldTpl = $(this.fieldTpl).html();
- this.buildForm( data.fields );
+ this.tpl = $(this.tpl).html();
+ this.fieldTpl = $(this.fieldTpl).html();
+ this.buildForm(data.fields);
- this.listenTo( this.model, 'error', this.saveError );
- },
+ this.listenTo(this.model, 'error', this.saveError);
+ },
/* Allows extended views to add custom
* init steps without needing to repeat
* default init steps
*/
- preRender: function( data ) {
+ preRender: function(data) {
/* Custom code goes here */
- return data;
- },
+ return data;
+ },
- render: function( html ) {
- var fields = html || '';
+ render: function(html) {
+ var fields = html || '';
- $(this.el).html( _.template(this.tpl)({
- fields: fields
- }));
+ $(this.el).html(_.template(this.tpl)({
+ fields: fields
+ }));
- this.postRender();
+ this.postRender();
- return this;
- },
+ return this;
+ },
- postRender: function() {
- var $container = $(this.el);
- this.$form = $container.find('form');
- this.$errors = $container.find('.submission-error');
- this.$submitButton = $container.find(this.submitButton);
- },
+ postRender: function() {
+ var $container = $(this.el);
+ this.$form = $container.find('form');
+ this.$errors = $container.find('.submission-error');
+ this.$submitButton = $container.find(this.submitButton);
+ },
- buildForm: function( data ) {
- var html = [],
- i,
- len = data.length,
- fieldTpl = this.fieldTpl;
+ buildForm: function(data) {
+ var html = [],
+ i,
+ len = data.length,
+ fieldTpl = this.fieldTpl;
- this.fields = data;
+ this.fields = data;
- for ( i=0; i
' + error.responseText + ''];
- this.setErrors();
- this.toggleDisableButton(false);
- },
+ focusFirstError: function() {
+ var $error = this.$form.find('.error').first(),
+ $field = {},
+ $parent = {};
- setErrors: function() {
- var $msg = this.$errors.find('.message-copy'),
- html = [],
- errors = this.errors,
- i,
- len = errors.length;
+ if ($error.is('label')) {
+ $parent = $error.parent('.form-field');
+ $error = $parent.find('input') || $parent.find('select');
+ } else {
+ $field = $error;
+ }
- for ( i=0; i' + error.responseText + ''];
+ this.setErrors();
+ this.toggleDisableButton(false);
+ },
+
+ setErrors: function() {
+ var $msg = this.$errors.find('.message-copy'),
+ html = [],
+ errors = this.errors,
+ i,
+ len = errors.length;
+
+ for (i = 0; i < len; i++) {
+ html.push(errors[i]);
+ }
+
+ $msg.html(html.join(''));
+
+ this.element.show(this.$errors);
// Scroll to error messages
- $('html,body').animate({
- scrollTop: this.$errors.offset().top
- },'slow');
+ $('html,body').animate({
+ scrollTop: this.$errors.offset().top
+ }, 'slow');
// Focus on first error field
- this.focusFirstError();
- },
+ this.focusFirstError();
+ },
/* Allows extended views to add non-form attributes
- * to the data before saving it to model
+ * to the data before saving it to model
*/
- setExtraData: function( data ) {
- return data;
- },
+ setExtraData: function(data) {
+ return data;
+ },
- submitForm: function( event ) {
- var data = this.getFormData();
+ submitForm: function(event) {
+ var data = this.getFormData();
- if (!_.isUndefined(event)) {
- event.preventDefault();
- }
+ if (!_.isUndefined(event)) {
+ event.preventDefault();
+ }
- this.toggleDisableButton(true);
+ this.toggleDisableButton(true);
- if ( !_.compact(this.errors).length ) {
- data = this.setExtraData( data );
- this.model.set( data );
- this.model.save();
- this.toggleErrorMsg( false );
- } else {
- this.toggleErrorMsg( true );
- }
+ if (!_.compact(this.errors).length) {
+ data = this.setExtraData(data);
+ this.model.set(data);
+ this.model.save();
+ this.toggleErrorMsg(false);
+ } else {
+ this.toggleErrorMsg(true);
+ }
- this.postFormSubmission();
- },
+ this.postFormSubmission();
+ },
/* Allows extended views to add custom
* code after form submission
*/
- postFormSubmission: function() {
- return true;
- },
+ postFormSubmission: function() {
+ return true;
+ },
- toggleErrorMsg: function( show ) {
- if ( show ) {
- this.setErrors();
- this.toggleDisableButton(false);
- } else {
- this.element.hide( this.$errors );
- }
- },
+ toggleErrorMsg: function(show) {
+ if (show) {
+ this.setErrors();
+ this.toggleDisableButton(false);
+ } else {
+ this.element.hide(this.$errors);
+ }
+ },
/**
* If a form button is defined for this form, this will disable the button on
@@ -265,15 +263,15 @@
* disabled (boolean): If set to TRUE, disable the button.
*
*/
- toggleDisableButton: function ( disabled ) {
- if (this.$submitButton) {
- this.$submitButton.attr('disabled', disabled);
- }
- },
+ toggleDisableButton: function(disabled) {
+ if (this.$submitButton) {
+ this.$submitButton.attr('disabled', disabled);
+ }
+ },
- validate: function( $el ) {
- return EdxUtilsValidate.validate( $el );
- }
+ validate: function($el) {
+ return EdxUtilsValidate.validate($el);
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/HintedLoginView.js b/lms/static/js/student_account/views/HintedLoginView.js
index bd35ddbad9..74793304e9 100644
--- a/lms/static/js/student_account/views/HintedLoginView.js
+++ b/lms/static/js/student_account/views/HintedLoginView.js
@@ -1,46 +1,45 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone'],
function($, _, Backbone) {
+ return Backbone.View.extend({
+ el: '#hinted-login-form',
- return Backbone.View.extend({
- el: '#hinted-login-form',
+ tpl: '#hinted_login-tpl',
- tpl: '#hinted_login-tpl',
+ events: {
+ 'click .proceed-button': 'proceedWithHintedAuth'
+ },
- events: {
- 'click .proceed-button': 'proceedWithHintedAuth'
- },
+ formType: 'hinted-login',
- formType: 'hinted-login',
-
- initialize: function( data ) {
- this.tpl = $(this.tpl).html();
- this.hintedProvider = (
+ initialize: function(data) {
+ this.tpl = $(this.tpl).html();
+ this.hintedProvider = (
_.findWhere(data.thirdPartyAuth.providers, {id: data.hintedProvider}) ||
_.findWhere(data.thirdPartyAuth.secondaryProviders, {id: data.hintedProvider})
);
- },
+ },
- render: function() {
- $(this.el).html(_.template(this.tpl)({
- hintedProvider: this.hintedProvider
- }));
+ render: function() {
+ $(this.el).html(_.template(this.tpl)({
+ hintedProvider: this.hintedProvider
+ }));
- return this;
- },
+ return this;
+ },
- proceedWithHintedAuth: function( event ) {
- this.redirect(this.hintedProvider.loginUrl);
- },
+ proceedWithHintedAuth: function(event) {
+ this.redirect(this.hintedProvider.loginUrl);
+ },
/**
* Redirect to a URL. Mainly useful for mocking out in tests.
* @param {string} url The URL to redirect to.
*/
- redirect: function( url ) {
- window.location.href = url;
- }
+ redirect: function(url) {
+ window.location.href = url;
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/InstitutionLoginView.js b/lms/static/js/student_account/views/InstitutionLoginView.js
index 8f191d5d3c..d466d15c19 100644
--- a/lms/static/js/student_account/views/InstitutionLoginView.js
+++ b/lms/static/js/student_account/views/InstitutionLoginView.js
@@ -1,28 +1,27 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['jquery', 'underscore', 'backbone'],
function($, _, Backbone) {
+ return Backbone.View.extend({
+ el: '#institution_login-form',
- return Backbone.View.extend({
- el: '#institution_login-form',
+ initialize: function(data) {
+ var tpl = data.mode == 'register' ? '#institution_register-tpl' : '#institution_login-tpl';
+ this.tpl = $(tpl).html();
+ this.providers = data.thirdPartyAuth.secondaryProviders || [];
+ this.platformName = data.platformName;
+ },
- initialize: function( data ) {
- var tpl = data.mode == "register" ? '#institution_register-tpl' : '#institution_login-tpl';
- this.tpl = $(tpl).html();
- this.providers = data.thirdPartyAuth.secondaryProviders || [];
- this.platformName = data.platformName;
- },
-
- render: function() {
- $(this.el).html(_.template(this.tpl)({
+ render: function() {
+ $(this.el).html(_.template(this.tpl)({
// We pass the context object to the template so that
// we can perform variable interpolation using sprintf
- providers: this.providers,
- platformName: this.platformName
- }));
+ providers: this.providers,
+ platformName: this.platformName
+ }));
- return this;
- }
+ return this;
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/LoginView.js b/lms/static/js/student_account/views/LoginView.js
index c62edc6787..05bbc2eca1 100644
--- a/lms/static/js/student_account/views/LoginView.js
+++ b/lms/static/js/student_account/views/LoginView.js
@@ -1,4 +1,4 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'jquery',
@@ -6,38 +6,38 @@
'gettext',
'edx-ui-toolkit/js/utils/html-utils',
'js/student_account/views/FormView'
- ],
+ ],
function($, _, gettext, HtmlUtils, FormView) {
- return FormView.extend({
- el: '#login-form',
- tpl: '#login-tpl',
- events: {
- 'click .js-login': 'submitForm',
- 'click .forgot-password': 'forgotPassword',
- 'click .login-provider': 'thirdPartyAuth'
- },
- formType: 'login',
- requiredStr: '',
- submitButton: '.js-login',
+ return FormView.extend({
+ el: '#login-form',
+ tpl: '#login-tpl',
+ events: {
+ 'click .js-login': 'submitForm',
+ 'click .forgot-password': 'forgotPassword',
+ 'click .login-provider': 'thirdPartyAuth'
+ },
+ formType: 'login',
+ requiredStr: '',
+ submitButton: '.js-login',
- preRender: function( data ) {
- this.providers = data.thirdPartyAuth.providers || [];
- this.hasSecondaryProviders = (
+ preRender: function(data) {
+ this.providers = data.thirdPartyAuth.providers || [];
+ this.hasSecondaryProviders = (
data.thirdPartyAuth.secondaryProviders && data.thirdPartyAuth.secondaryProviders.length
);
- this.currentProvider = data.thirdPartyAuth.currentProvider || '';
- this.errorMessage = data.thirdPartyAuth.errorMessage || '';
- this.platformName = data.platformName;
- this.resetModel = data.resetModel;
- this.supportURL = data.supportURL;
+ this.currentProvider = data.thirdPartyAuth.currentProvider || '';
+ this.errorMessage = data.thirdPartyAuth.errorMessage || '';
+ this.platformName = data.platformName;
+ this.resetModel = data.resetModel;
+ this.supportURL = data.supportURL;
- this.listenTo( this.model, 'sync', this.saveSuccess );
- this.listenTo( this.resetModel, 'sync', this.resetEmail );
- },
+ this.listenTo(this.model, 'sync', this.saveSuccess);
+ this.listenTo(this.resetModel, 'sync', this.resetEmail);
+ },
- render: function( html ) {
- var fields = html || '';
- this.successMessage = HtmlUtils.interpolateHtml(
+ render: function(html) {
+ var fields = html || '';
+ this.successMessage = HtmlUtils.interpolateHtml(
// eslint-disable-next-line
gettext('We have sent an email message with password reset instructions to the email address you provided. If you do not receive this message, {anchorStart}contact technical support{anchorEnd}.'), { // eslint-disable-line max-len
anchorStart: HtmlUtils.HTML(''),
@@ -45,91 +45,91 @@
}
);
- $(this.el).html(_.template(this.tpl)({
+ $(this.el).html(_.template(this.tpl)({
// We pass the context object to the template so that
// we can perform variable interpolation using sprintf
- context: {
- fields: fields,
- currentProvider: this.currentProvider,
- errorMessage: this.errorMessage,
- providers: this.providers,
- hasSecondaryProviders: this.hasSecondaryProviders,
- platformName: this.platformName
- }
- }));
+ context: {
+ fields: fields,
+ currentProvider: this.currentProvider,
+ errorMessage: this.errorMessage,
+ providers: this.providers,
+ hasSecondaryProviders: this.hasSecondaryProviders,
+ platformName: this.platformName
+ }
+ }));
- this.postRender();
+ this.postRender();
- return this;
- },
+ return this;
+ },
- postRender: function() {
- this.$container = $(this.el);
+ postRender: function() {
+ this.$container = $(this.el);
- this.$form = this.$container.find('form');
- this.$errors = this.$container.find('.submission-error');
- this.$resetSuccess = this.$container.find('.js-reset-success');
- this.$authError = this.$container.find('.already-authenticated-msg');
- this.$submitButton = this.$container.find(this.submitButton);
+ this.$form = this.$container.find('form');
+ this.$errors = this.$container.find('.submission-error');
+ this.$resetSuccess = this.$container.find('.js-reset-success');
+ this.$authError = this.$container.find('.already-authenticated-msg');
+ this.$submitButton = this.$container.find(this.submitButton);
/* If we're already authenticated with a third-party
* provider, try logging in. The easiest way to do this
* is to simply submit the form.
*/
- if (this.currentProvider) {
- this.model.save();
- }
- },
+ if (this.currentProvider) {
+ this.model.save();
+ }
+ },
- forgotPassword: function( event ) {
- event.preventDefault();
+ forgotPassword: function(event) {
+ event.preventDefault();
- this.trigger('password-help');
- this.element.hide( this.$resetSuccess );
- },
+ this.trigger('password-help');
+ this.element.hide(this.$resetSuccess);
+ },
- postFormSubmission: function() {
- this.element.hide( this.$resetSuccess );
- },
+ postFormSubmission: function() {
+ this.element.hide(this.$resetSuccess);
+ },
- resetEmail: function() {
- this.element.hide( this.$errors );
- this.resetMessage = this.$resetSuccess.find('.message-copy');
- if (this.resetMessage.find('p').length === 0) {
- this.resetMessage.append(
+ resetEmail: function() {
+ this.element.hide(this.$errors);
+ this.resetMessage = this.$resetSuccess.find('.message-copy');
+ if (this.resetMessage.find('p').length === 0) {
+ this.resetMessage.append(
HtmlUtils.joinHtml(
HtmlUtils.HTML(''),
this.successMessage,
HtmlUtils.HTML('
')
).toString()
);
- }
- this.element.show( this.$resetSuccess );
- },
+ }
+ this.element.show(this.$resetSuccess);
+ },
- thirdPartyAuth: function( event ) {
- var providerUrl = $(event.currentTarget).data('provider-url') || '';
+ thirdPartyAuth: function(event) {
+ var providerUrl = $(event.currentTarget).data('provider-url') || '';
- if (providerUrl) {
- window.location.href = providerUrl;
- }
- },
+ if (providerUrl) {
+ window.location.href = providerUrl;
+ }
+ },
- saveSuccess: function() {
- this.trigger('auth-complete');
- this.element.hide( this.$resetSuccess );
- },
+ saveSuccess: function() {
+ this.trigger('auth-complete');
+ this.element.hide(this.$resetSuccess);
+ },
- saveError: function( error ) {
- var msg = error.responseText;
- if (error.status === 0) {
- msg = gettext('An error has occurred. Check your Internet connection and try again.');
- } else if(error.status === 500){
- msg = gettext('An error has occurred. Try refreshing the page, or check your Internet connection.');
- }
- this.errors = ['' + msg + ''];
- this.setErrors();
- this.element.hide( this.$resetSuccess );
+ saveError: function(error) {
+ var msg = error.responseText;
+ if (error.status === 0) {
+ msg = gettext('An error has occurred. Check your Internet connection and try again.');
+ } else if (error.status === 500) {
+ msg = gettext('An error has occurred. Try refreshing the page, or check your Internet connection.');
+ }
+ this.errors = ['' + msg + ''];
+ this.setErrors();
+ this.element.hide(this.$resetSuccess);
/* If we've gotten a 403 error, it means that we've successfully
* authenticated with a third-party provider, but we haven't
@@ -137,17 +137,17 @@
* we need to prompt the user to enter a little more information
* to complete the registration process.
*/
- if ( error.status === 403 &&
+ if (error.status === 403 &&
error.responseText === 'third-party-auth' &&
- this.currentProvider ) {
- this.element.show( this.$authError );
- this.element.hide( this.$errors );
- } else {
- this.element.hide( this.$authError );
- this.element.show( this.$errors );
+ this.currentProvider) {
+ this.element.show(this.$authError);
+ this.element.hide(this.$errors);
+ } else {
+ this.element.hide(this.$authError);
+ this.element.show(this.$errors);
+ }
+ this.toggleDisableButton(false);
}
- this.toggleDisableButton(false);
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/PasswordResetView.js b/lms/static/js/student_account/views/PasswordResetView.js
index c7b11b2298..32a0ee9956 100644
--- a/lms/static/js/student_account/views/PasswordResetView.js
+++ b/lms/static/js/student_account/views/PasswordResetView.js
@@ -1,48 +1,47 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'js/student_account/views/FormView'
- ],
+ 'jquery',
+ 'js/student_account/views/FormView'
+ ],
function($, FormView) {
+ return FormView.extend({
+ el: '#password-reset-form',
- return FormView.extend({
- el: '#password-reset-form',
+ tpl: '#password_reset-tpl',
- tpl: '#password_reset-tpl',
+ events: {
+ 'click .js-reset': 'submitForm'
+ },
- events: {
- 'click .js-reset': 'submitForm'
- },
+ formType: 'password-reset',
- formType: 'password-reset',
+ requiredStr: '',
- requiredStr: '',
+ submitButton: '.js-reset',
- submitButton: '.js-reset',
+ preRender: function() {
+ this.element.show($(this.el));
+ this.element.show($(this.el).parent());
+ this.listenTo(this.model, 'sync', this.saveSuccess);
+ },
- preRender: function() {
- this.element.show( $( this.el ) );
- this.element.show( $( this.el ).parent() );
- this.listenTo( this.model, 'sync', this.saveSuccess );
- },
+ toggleErrorMsg: function(show) {
+ if (show) {
+ this.setErrors();
+ this.toggleDisableButton(false);
+ } else {
+ this.element.hide(this.$errors);
+ }
+ },
- toggleErrorMsg: function( show ) {
- if ( show ) {
- this.setErrors();
- this.toggleDisableButton(false);
- } else {
- this.element.hide( this.$errors );
- }
- },
-
- saveSuccess: function() {
- this.trigger('password-email-sent');
+ saveSuccess: function() {
+ this.trigger('password-email-sent');
// Destroy the view (but not el) and unbind events
- this.$el.empty().off();
- this.stopListening();
- }
+ this.$el.empty().off();
+ this.stopListening();
+ }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/RegisterView.js b/lms/static/js/student_account/views/RegisterView.js
index 96d43a78f3..8b03015732 100644
--- a/lms/static/js/student_account/views/RegisterView.js
+++ b/lms/static/js/student_account/views/RegisterView.js
@@ -1,85 +1,84 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
- 'jquery',
- 'underscore',
- 'js/student_account/views/FormView'
- ],
+ 'jquery',
+ 'underscore',
+ 'js/student_account/views/FormView'
+ ],
function($, _, FormView) {
+ return FormView.extend({
+ el: '#register-form',
- return FormView.extend({
- el: '#register-form',
+ tpl: '#register-tpl',
- tpl: '#register-tpl',
+ events: {
+ 'click .js-register': 'submitForm',
+ 'click .login-provider': 'thirdPartyAuth'
+ },
- events: {
- 'click .js-register': 'submitForm',
- 'click .login-provider': 'thirdPartyAuth'
- },
+ formType: 'register',
- formType: 'register',
+ submitButton: '.js-register',
- submitButton: '.js-register',
-
- preRender: function( data ) {
- this.providers = data.thirdPartyAuth.providers || [];
- this.hasSecondaryProviders = (
+ preRender: function(data) {
+ this.providers = data.thirdPartyAuth.providers || [];
+ this.hasSecondaryProviders = (
data.thirdPartyAuth.secondaryProviders && data.thirdPartyAuth.secondaryProviders.length
);
- this.currentProvider = data.thirdPartyAuth.currentProvider || '';
- this.errorMessage = data.thirdPartyAuth.errorMessage || '';
- this.platformName = data.platformName;
- this.autoSubmit = data.thirdPartyAuth.autoSubmitRegForm;
+ this.currentProvider = data.thirdPartyAuth.currentProvider || '';
+ this.errorMessage = data.thirdPartyAuth.errorMessage || '';
+ this.platformName = data.platformName;
+ this.autoSubmit = data.thirdPartyAuth.autoSubmitRegForm;
- this.listenTo( this.model, 'sync', this.saveSuccess );
- },
+ this.listenTo(this.model, 'sync', this.saveSuccess);
+ },
- render: function( html ) {
- var fields = html || '';
+ render: function(html) {
+ var fields = html || '';
- $(this.el).html(_.template(this.tpl)({
+ $(this.el).html(_.template(this.tpl)({
/* We pass the context object to the template so that
* we can perform variable interpolation using sprintf
*/
- context: {
- fields: fields,
- currentProvider: this.currentProvider,
- errorMessage: this.errorMessage,
- providers: this.providers,
- hasSecondaryProviders: this.hasSecondaryProviders,
- platformName: this.platformName
+ context: {
+ fields: fields,
+ currentProvider: this.currentProvider,
+ errorMessage: this.errorMessage,
+ providers: this.providers,
+ hasSecondaryProviders: this.hasSecondaryProviders,
+ platformName: this.platformName
+ }
+ }));
+
+ this.postRender();
+
+ if (this.autoSubmit) {
+ $(this.el).hide();
+ $('#register-honor_code').prop('checked', true);
+ this.submitForm();
}
- }));
- this.postRender();
+ return this;
+ },
- if (this.autoSubmit) {
- $(this.el).hide();
- $('#register-honor_code').prop('checked', true);
- this.submitForm();
- }
+ thirdPartyAuth: function(event) {
+ var providerUrl = $(event.currentTarget).data('provider-url') || '';
- return this;
- },
+ if (providerUrl) {
+ window.location.href = providerUrl;
+ }
+ },
- thirdPartyAuth: function( event ) {
- var providerUrl = $(event.currentTarget).data('provider-url') || '';
+ saveSuccess: function() {
+ this.trigger('auth-complete');
+ },
- if ( providerUrl ) {
- window.location.href = providerUrl;
- }
- },
-
- saveSuccess: function() {
- this.trigger('auth-complete');
- },
-
- saveError: function( error ) {
- $(this.el).show(); // Show in case the form was hidden for auto-submission
- this.errors = _.flatten(
+ saveError: function(error) {
+ $(this.el).show(); // Show in case the form was hidden for auto-submission
+ this.errors = _.flatten(
_.map(
// Something is passing this 'undefined'. Protect against this.
- JSON.parse(error.responseText || "[]"),
+ JSON.parse(error.responseText || '[]'),
function(error_list) {
return _.map(
error_list,
@@ -88,16 +87,16 @@
}
)
);
- this.setErrors();
- this.toggleDisableButton(false);
- },
+ this.setErrors();
+ this.toggleDisableButton(false);
+ },
- postFormSubmission: function() {
- if (_.compact(this.errors).length) {
+ postFormSubmission: function() {
+ if (_.compact(this.errors).length) {
// The form did not get submitted due to validation errors.
- $(this.el).show(); // Show in case the form was hidden for auto-submission
+ $(this.el).show(); // Show in case the form was hidden for auto-submission
+ }
}
- }
+ });
});
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_account/views/account_section_view.js b/lms/static/js/student_account/views/account_section_view.js
index 4164c81c77..cd022eee9d 100644
--- a/lms/static/js/student_account/views/account_section_view.js
+++ b/lms/static/js/student_account/views/account_section_view.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -6,15 +6,14 @@
'underscore',
'backbone',
'text!templates/student_account/account_settings_section.underscore'
- ], function (gettext, $, _, Backbone, sectionTemplate) {
-
+ ], function(gettext, $, _, Backbone, sectionTemplate) {
var AccountSectionView = Backbone.View.extend({
- initialize: function (options) {
+ initialize: function(options) {
this.options = options;
},
- render: function () {
+ render: function() {
this.$el.html(_.template(sectionTemplate)({
sections: this.options.sections,
activeTabName: this.options.activeTabName
diff --git a/lms/static/js/student_account/views/account_settings_factory.js b/lms/static/js/student_account/views/account_settings_factory.js
index 1f93bf0541..d9d464f3e2 100644
--- a/lms/static/js/student_account/views/account_settings_factory.js
+++ b/lms/static/js/student_account/views/account_settings_factory.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'logger',
@@ -7,10 +7,9 @@
'js/student_account/views/account_settings_fields',
'js/student_account/views/account_settings_view',
'edx-ui-toolkit/js/utils/string-utils'
- ], function (gettext, $, _, Backbone, Logger, UserAccountModel, UserPreferencesModel,
+ ], function(gettext, $, _, Backbone, Logger, UserAccountModel, UserPreferencesModel,
AccountSettingsFieldViews, AccountSettingsView, StringUtils) {
-
- return function (
+ return function(
fieldsData,
ordersHistoryData,
authData,
@@ -32,7 +31,7 @@
userPreferencesModel.url = userPreferencesApiUrl;
aboutSectionsData = [
- {
+ {
title: gettext('Basic Account Information'),
subtitle: gettext('These settings include basic information about your account. You can also specify additional information and see your linked social accounts on this page.'), // eslint-disable-line max-len
fields: [
@@ -243,10 +242,10 @@
accountSettingsView.render();
- showAccountSettingsPage = function () {
+ showAccountSettingsPage = function() {
// Record that the account settings page was viewed.
Logger.log('edx.user.settings.viewed', {
- page: "account",
+ page: 'account',
visibility: null,
user_id: accountUserId
});
@@ -255,12 +254,12 @@
accountSettingsView.renderFields();
};
- showLoadingError = function () {
+ showLoadingError = function() {
accountSettingsView.showLoadingError();
};
userAccountModel.fetch({
- success: function () {
+ success: function() {
// Fetch the user preferences model
userPreferencesModel.fetch({
success: showAccountSettingsPage,
diff --git a/lms/static/js/student_account/views/account_settings_fields.js b/lms/static/js/student_account/views/account_settings_fields.js
index dbfff2172f..4262fa7330 100644
--- a/lms/static/js/student_account/views/account_settings_fields.js
+++ b/lms/static/js/student_account/views/account_settings_fields.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -14,7 +14,7 @@
'text!templates/fields/field_order_history.underscore',
'edx-ui-toolkit/js/utils/string-utils',
'edx-ui-toolkit/js/utils/html-utils'
- ], function (
+ ], function(
gettext, $, _, Backbone,
FieldViews,
field_text_account_template,
@@ -27,7 +27,6 @@
HtmlUtils
)
{
-
var AccountSettingsFieldViews = {
ReadonlyFieldView: FieldViews.ReadonlyFieldView.extend({
fieldTemplate: field_readonly_account_template
@@ -40,7 +39,7 @@
}),
EmailFieldView: FieldViews.TextFieldView.extend({
fieldTemplate: field_text_account_template,
- successMessage: function () {
+ successMessage: function() {
return HtmlUtils.joinHtml(
this.indicators.success,
StringUtils.interpolate(
@@ -52,7 +51,7 @@
}),
LanguagePreferenceFieldView: FieldViews.DropdownFieldView.extend({
fieldTemplate: field_dropdown_account_template,
- saveSucceeded: function () {
+ saveSucceeded: function() {
var data = {
'language': this.modelValue()
};
@@ -63,10 +62,10 @@
url: '/i18n/setlang/',
data: data,
dataType: 'html',
- success: function () {
+ success: function() {
view.showSuccessMessage();
},
- error: function () {
+ error: function() {
view.showNotificationMessage(
HtmlUtils.joinHtml(
view.indicators.error,
@@ -84,16 +83,16 @@
events: {
'click button': 'linkClicked'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
this._super(options);
_.bindAll(this, 'resetPassword');
},
- linkClicked: function (event) {
+ linkClicked: function(event) {
event.preventDefault();
this.resetPassword(event);
},
- resetPassword: function () {
+ resetPassword: function() {
var data = {};
data[this.options.emailAttribute] = this.model.get(this.options.emailAttribute);
@@ -102,15 +101,15 @@
type: 'POST',
url: view.options.linkHref,
data: data,
- success: function () {
+ success: function() {
view.showSuccessMessage();
},
- error: function (xhr) {
+ error: function(xhr) {
view.showErrorMessage(xhr);
}
});
},
- successMessage: function () {
+ successMessage: function() {
return HtmlUtils.joinHtml(
this.indicators.success,
StringUtils.interpolate(
@@ -122,7 +121,7 @@
}),
LanguageProficienciesFieldView: FieldViews.DropdownFieldView.extend({
fieldTemplate: field_dropdown_account_template,
- modelValue: function () {
+ modelValue: function() {
var modelValue = this.model.get(this.options.valueAttribute);
if (_.isArray(modelValue) && modelValue.length > 0) {
return modelValue[0].code;
@@ -130,7 +129,7 @@
return null;
}
},
- saveValue: function () {
+ saveValue: function() {
if (this.persistChanges === true) {
var attributes = {},
value = this.fieldValue() ? [{'code': this.fieldValue()}] : [];
@@ -141,20 +140,20 @@
}),
AuthFieldView: FieldViews.LinkFieldView.extend({
fieldTemplate: field_social_link_template,
- className: function () {
+ className: function() {
return 'u-field u-field-social u-field-' + this.options.valueAttribute;
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
this._super(options);
_.bindAll(this, 'redirect_to', 'disconnect', 'successMessage', 'inProgressMessage');
},
- render: function () {
+ render: function() {
var linkTitle = '',
linkClass = '',
subTitle = '',
screenReaderTitle = StringUtils.interpolate(
- gettext("Link your {accountName} account"),
+ gettext('Link your {accountName} account'),
{accountName: this.options.title}
);
if (this.options.connected) {
@@ -165,7 +164,7 @@
{accountName: this.options.title, platformName: this.options.platformName}
);
screenReaderTitle = StringUtils.interpolate(
- gettext("Unlink your {accountName} account"),
+ gettext('Unlink your {accountName} account'),
{accountName: this.options.title}
);
} else if (this.options.acceptsLogins) {
@@ -190,7 +189,7 @@
this.delegateEvents();
return this;
},
- linkClicked: function (event) {
+ linkClicked: function(event) {
event.preventDefault();
this.showInProgressMessage();
@@ -203,10 +202,10 @@
this.redirect_to(this.options.connectUrl);
}
},
- redirect_to: function (url) {
+ redirect_to: function(url) {
window.location.href = url;
},
- disconnect: function () {
+ disconnect: function() {
var data = {};
// Disconnects the provider from the user's edX account.
@@ -217,22 +216,22 @@
url: this.options.disconnectUrl,
data: data,
dataType: 'html',
- success: function () {
+ success: function() {
view.options.connected = false;
view.render();
view.showSuccessMessage();
},
- error: function (xhr) {
+ error: function(xhr) {
view.showErrorMessage(xhr);
}
});
},
- inProgressMessage: function () {
+ inProgressMessage: function() {
return HtmlUtils.joinHtml(this.indicators.inProgress, (
this.options.connected ? gettext('Unlinking') : gettext('Linking')
));
},
- successMessage: function () {
+ successMessage: function() {
return HtmlUtils.joinHtml(this.indicators.success, gettext('Successfully unlinked.'));
}
}),
@@ -241,13 +240,13 @@
fieldType: 'orderHistory',
fieldTemplate: field_order_history_template,
- initialize: function (options) {
+ initialize: function(options) {
this.options = options;
this._super(options);
this.template = HtmlUtils.template(this.fieldTemplate);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, this.template({
title: this.options.title,
totalPrice: this.options.totalPrice,
diff --git a/lms/static/js/student_account/views/account_settings_view.js b/lms/static/js/student_account/views/account_settings_view.js
index 8b9f387e7f..3271154c67 100644
--- a/lms/static/js/student_account/views/account_settings_view.js
+++ b/lms/static/js/student_account/views/account_settings_view.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -8,8 +8,7 @@
'edx-ui-toolkit/js/utils/html-utils',
'js/student_account/views/account_section_view',
'text!templates/student_account/account_settings.underscore'
- ], function (gettext, $, _, Backbone, HtmlUtils, AccountSectionView, accountSettingsTemplate) {
-
+ ], function(gettext, $, _, Backbone, HtmlUtils, AccountSectionView, accountSettingsTemplate) {
var AccountSettingsView = Backbone.View.extend({
navLink: '.account-nav-link',
@@ -23,12 +22,12 @@
'click .account-nav-link': 'changeTab'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = options;
_.bindAll(this, 'render', 'changeTab', 'renderFields', 'showLoadingError');
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(accountSettingsTemplate)({
accountSettingsTabs: this.accountSettingsTabs
}));
@@ -49,10 +48,10 @@
$currentTab.addClass('active');
$(this.navLink).removeAttr('aria-describedby');
- $currentTab.attr('aria-describedby', 'header-subtitle-'+this.activeTab);
+ $currentTab.attr('aria-describedby', 'header-subtitle-' + this.activeTab);
},
- renderSection: function (tabSections) {
+ renderSection: function(tabSections) {
var accountSectionView = new AccountSectionView({
activeTabName: this.activeTab,
sections: tabSections,
@@ -62,19 +61,19 @@
accountSectionView.render();
},
- renderFields: function () {
+ renderFields: function() {
var view = this;
view.$('.ui-loading-indicator').addClass('is-hidden');
- _.each(view.$('.account-settings-section-body'), function (sectionEl, index) {
- _.each(view.options.tabSections[view.activeTab][index].fields, function (field) {
+ _.each(view.$('.account-settings-section-body'), function(sectionEl, index) {
+ _.each(view.options.tabSections[view.activeTab][index].fields, function(field) {
$(sectionEl).append(field.view.render().el);
});
});
return this;
},
- showLoadingError: function () {
+ showLoadingError: function() {
this.$('.ui-loading-indicator').addClass('is-hidden');
this.$('.ui-loading-error').removeClass('is-hidden');
}
diff --git a/lms/static/js/student_account/views/finish_auth_factory.js b/lms/static/js/student_account/views/finish_auth_factory.js
index aa4ffbff9a..a6e62a098b 100644
--- a/lms/static/js/student_account/views/finish_auth_factory.js
+++ b/lms/static/js/student_account/views/finish_auth_factory.js
@@ -1,8 +1,8 @@
-(function (define) {
+(function(define) {
'use strict';
- define("js/student_account/views/finish_auth_factory",
+ define('js/student_account/views/finish_auth_factory',
['jquery', 'underscore', 'backbone', 'js/student_account/views/FinishAuthView', 'utility'],
- function ($, _, Backbone, FinishAuthView) {
+ function($, _, Backbone, FinishAuthView) {
return function() {
var view = new FinishAuthView({});
view.render();
diff --git a/lms/static/js/student_profile/models/badges_model.js b/lms/static/js/student_profile/models/badges_model.js
index 8b127824d4..efb44d0c35 100644
--- a/lms/static/js/student_profile/models/badges_model.js
+++ b/lms/static/js/student_profile/models/badges_model.js
@@ -1,7 +1,6 @@
-;(function (define) {
+(function(define) {
'use strict';
define(['backbone'], function(Backbone) {
-
var BadgesModel = Backbone.Model.extend({});
return BadgesModel;
});
diff --git a/lms/static/js/student_profile/views/badge_list_container.js b/lms/static/js/student_profile/views/badge_list_container.js
index 528f03c548..b7607e7d59 100644
--- a/lms/static/js/student_profile/views/badge_list_container.js
+++ b/lms/static/js/student_profile/views/badge_list_container.js
@@ -1,10 +1,10 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'common/js/components/views/paginated_view',
'js/student_profile/views/badge_view', 'js/student_profile/views/badge_list_view',
'text!templates/student_profile/badge_list.underscore'],
- function (gettext, $, _, PaginatedView, BadgeView, BadgeListView, BadgeListTemplate) {
+ function(gettext, $, _, PaginatedView, BadgeView, BadgeListView, BadgeListTemplate) {
var BadgeListContainer = PaginatedView.extend({
type: 'badge',
@@ -18,7 +18,7 @@
paginationLabel: gettext('Accomplishments Pagination'),
- initialize: function (options) {
+ initialize: function(options) {
BadgeListContainer.__super__.initialize.call(this, options);
this.listView.find_courses_url = options.find_courses_url;
this.listView.badgeMeta = options.badgeMeta;
diff --git a/lms/static/js/student_profile/views/badge_list_view.js b/lms/static/js/student_profile/views/badge_list_view.js
index 603b04cd42..40aa50d5b2 100644
--- a/lms/static/js/student_profile/views/badge_list_view.js
+++ b/lms/static/js/student_profile/views/badge_list_view.js
@@ -1,28 +1,28 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
- 'gettext',
- 'jquery',
- 'underscore',
- 'edx-ui-toolkit/js/utils/html-utils',
- 'common/js/components/views/list',
- 'js/student_profile/views/badge_view',
- 'text!templates/student_profile/badge_placeholder.underscore'
- ],
- function (gettext, $, _, HtmlUtils, ListView, BadgeView, badgePlaceholder) {
+ 'gettext',
+ 'jquery',
+ 'underscore',
+ 'edx-ui-toolkit/js/utils/html-utils',
+ 'common/js/components/views/list',
+ 'js/student_profile/views/badge_view',
+ 'text!templates/student_profile/badge_placeholder.underscore'
+ ],
+ function(gettext, $, _, HtmlUtils, ListView, BadgeView, badgePlaceholder) {
var BadgeListView = ListView.extend({
tagName: 'div',
-
+
template: HtmlUtils.template(badgePlaceholder),
-
- renderCollection: function () {
+
+ renderCollection: function() {
var self = this,
$row;
this.$el.empty();
// Split into two columns.
- this.collection.each(function (badge, index) {
+ this.collection.each(function(badge, index) {
if (index % 2 === 0) {
$row = $('');
this.$el.append($row);
diff --git a/lms/static/js/student_profile/views/badge_view.js b/lms/static/js/student_profile/views/badge_view.js
index 5e3d4d0313..6c456c1a84 100644
--- a/lms/static/js/student_profile/views/badge_view.js
+++ b/lms/static/js/student_profile/views/badge_view.js
@@ -1,10 +1,9 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'moment',
'text!templates/student_profile/badge.underscore',
'js/student_profile/views/share_modal_view'],
- function (gettext, $, _, Backbone, Moment, badgeTemplate, ShareModalView) {
-
+ function(gettext, $, _, Backbone, Moment, badgeTemplate, ShareModalView) {
var BadgeView = Backbone.View.extend({
initialize: function(options) {
this.options = _.extend({}, options);
@@ -31,7 +30,7 @@
$('body').append(modal.$el);
modal.$el.fadeIn('short', 'swing', _.bind(modal.ready, modal));
},
- render: function () {
+ render: function() {
this.$el.html(this.template(this.context));
this.shareButton = this.$el.find('.share-button');
return this;
diff --git a/lms/static/js/student_profile/views/learner_profile_factory.js b/lms/static/js/student_profile/views/learner_profile_factory.js
index 9ebcbee153..a83e594e6d 100644
--- a/lms/static/js/student_profile/views/learner_profile_factory.js
+++ b/lms/static/js/student_profile/views/learner_profile_factory.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext',
@@ -17,12 +17,10 @@
'js/student_account/views/account_settings_fields',
'js/views/message_banner',
'string_utils'
- ], function (gettext, $, _, Backbone, Logger, PagingCollection, AccountSettingsModel, AccountPreferencesModel,
+ ], function(gettext, $, _, Backbone, Logger, PagingCollection, AccountSettingsModel, AccountPreferencesModel,
FieldsView, LearnerProfileFieldsView, LearnerProfileView, BadgeModel, BadgeListContainer,
AccountSettingsFieldViews, MessageBannerView) {
-
- return function (options) {
-
+ return function(options) {
var learnerProfileElement = $('.wrapper-profile');
var accountSettingsModel = new AccountSettingsModel(
@@ -56,7 +54,7 @@
title: interpolate_text(
gettext('{platform_name} learners can see my:'), {platform_name: options.platform_name}
),
- valueAttribute: "account_privacy",
+ valueAttribute: 'account_privacy',
options: [
['private', gettext('Limited Profile')],
['all_users', gettext('Full Profile')]
@@ -78,10 +76,10 @@
});
var usernameFieldView = new FieldsView.ReadonlyFieldView({
- model: accountSettingsModel,
- screenReaderTitle: gettext('Username'),
- valueAttribute: "username",
- helpMessage: ""
+ model: accountSettingsModel,
+ screenReaderTitle: gettext('Username'),
+ valueAttribute: 'username',
+ helpMessage: ''
});
var sectionOneFieldViews = [
@@ -94,7 +92,7 @@
showMessages: false,
iconName: 'fa-map-marker',
placeholderValue: gettext('Add Country'),
- valueAttribute: "country",
+ valueAttribute: 'country',
options: options.country_options,
helpMessage: '',
persistChanges: true
@@ -108,7 +106,7 @@
showMessages: false,
iconName: 'fa-comment',
placeholderValue: gettext('Add language'),
- valueAttribute: "language_proficiencies",
+ valueAttribute: 'language_proficiencies',
options: options.language_options,
helpMessage: '',
persistChanges: true
@@ -122,7 +120,7 @@
showMessages: false,
title: gettext('About me'),
placeholderValue: gettext("Tell other learners a little about yourself: where you live, what your interests are, why you're taking courses, or what you hope to learn."),
- valueAttribute: "bio",
+ valueAttribute: 'bio',
helpMessage: '',
persistChanges: true,
messagePosition: 'header'
@@ -174,7 +172,7 @@
var showLearnerProfileView = function() {
// Record that the profile page was viewed
Logger.log('edx.user.settings.viewed', {
- page: "profile",
+ page: 'profile',
visibility: getProfileVisibility(),
user_id: options.profile_user_id
});
diff --git a/lms/static/js/student_profile/views/learner_profile_fields.js b/lms/static/js/student_profile/views/learner_profile_fields.js
index c57d62e1e0..da18d97d7f 100644
--- a/lms/static/js/student_profile/views/learner_profile_fields.js
+++ b/lms/static/js/student_profile/views/learner_profile_fields.js
@@ -1,22 +1,21 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'edx-ui-toolkit/js/utils/string-utils',
'edx-ui-toolkit/js/utils/html-utils', 'js/views/fields', 'js/views/image_field', 'backbone-super'
- ], function (gettext, $, _, Backbone, StringUtils, HtmlUtils, FieldViews, ImageFieldView) {
-
+ ], function(gettext, $, _, Backbone, StringUtils, HtmlUtils, FieldViews, ImageFieldView) {
var LearnerProfileFieldViews = {};
LearnerProfileFieldViews.AccountPrivacyFieldView = FieldViews.DropdownFieldView.extend({
- render: function () {
+ render: function() {
this._super();
this.showNotificationMessage();
this.updateFieldValue();
return this;
},
- showNotificationMessage: function () {
+ showNotificationMessage: function() {
var accountSettingsLink = HtmlUtils.joinHtml(
HtmlUtils.interpolateHtml(
HtmlUtils.HTML('
'), {settings_url: this.options.accountSettingsPageUrl}
@@ -28,7 +27,7 @@
this._super(
HtmlUtils.interpolateHtml(
gettext('You must specify your birth year before you can share your full profile. To specify your birth year, go to the {account_settings_page_link}'), // eslint-disable-line max-len
- {'account_settings_page_link':accountSettingsLink}
+ {'account_settings_page_link': accountSettingsLink}
)
);
} else if (this.requiresParentalConsent) {
@@ -56,35 +55,35 @@
screenReaderTitle: gettext('Profile Image'),
- imageUrl: function () {
+ imageUrl: function() {
return this.model.profileImageUrl();
},
- imageAltText: function () {
+ imageAltText: function() {
return interpolate_text(
- gettext("Profile image for {username}"), {username: this.model.get('username')}
+ gettext('Profile image for {username}'), {username: this.model.get('username')}
);
},
- imageChangeSucceeded: function (e, data) {
+ imageChangeSucceeded: function(e, data) {
var view = this;
// Update model to get the latest urls of profile image.
- this.model.fetch().done(function () {
+ this.model.fetch().done(function() {
view.setCurrentStatus('');
view.render();
view.$('.u-field-upload-button').focus();
- }).fail(function () {
+ }).fail(function() {
view.setCurrentStatus('');
view.showErrorMessage(view.errorMessage);
});
},
- imageChangeFailed: function (e, data) {
+ imageChangeFailed: function(e, data) {
this.setCurrentStatus('');
this.showImageChangeFailedMessage(data.jqXHR.status, data.jqXHR.responseText);
},
- showImageChangeFailedMessage: function (status, responseText) {
+ showImageChangeFailedMessage: function(status, responseText) {
if (_.contains([400, 404], status)) {
try {
var errors = JSON.parse(responseText);
@@ -97,24 +96,24 @@
}
},
- showErrorMessage: function (message) {
+ showErrorMessage: function(message) {
this.options.messageView.showMessage(message);
},
- isEditingAllowed: function () {
+ isEditingAllowed: function() {
return this.model.isAboveMinimumAge();
},
- isShowingPlaceholder: function () {
+ isShowingPlaceholder: function() {
return !this.model.hasProfileImage();
},
- clickedRemoveButton: function (e, data) {
+ clickedRemoveButton: function(e, data) {
this.options.messageView.hideMessage();
this._super(e, data);
},
- fileSelected: function (e, data) {
+ fileSelected: function(e, data) {
this.options.messageView.hideMessage();
this._super(e, data);
}
diff --git a/lms/static/js/student_profile/views/learner_profile_view.js b/lms/static/js/student_profile/views/learner_profile_view.js
index 05d015621a..d840b6865e 100644
--- a/lms/static/js/student_profile/views/learner_profile_view.js
+++ b/lms/static/js/student_profile/views/learner_profile_view.js
@@ -1,140 +1,138 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'edx-ui-toolkit/js/utils/html-utils',
'common/js/components/views/tabbed_view',
'js/student_profile/views/section_two_tab',
'text!templates/student_profile/learner_profile.underscore'],
- function (gettext, $, _, Backbone, HtmlUtils, TabbedView, SectionTwoTab, learnerProfileTemplate) {
+ function(gettext, $, _, Backbone, HtmlUtils, TabbedView, SectionTwoTab, learnerProfileTemplate) {
+ var LearnerProfileView = Backbone.View.extend({
- var LearnerProfileView = Backbone.View.extend({
+ initialize: function(options) {
+ this.options = _.extend({}, options);
+ _.bindAll(this, 'showFullProfile', 'render', 'renderFields', 'showLoadingError');
+ this.listenTo(this.options.preferencesModel, 'change:' + 'account_privacy', this.render);
+ var Router = Backbone.Router.extend({
+ routes: {':about_me': 'loadTab', ':accomplishments': 'loadTab'}
+ });
- initialize: function (options) {
- this.options = _.extend({}, options);
- _.bindAll(this, 'showFullProfile', 'render', 'renderFields', 'showLoadingError');
- this.listenTo(this.options.preferencesModel, "change:" + 'account_privacy', this.render);
- var Router = Backbone.Router.extend({
- routes: {":about_me": "loadTab", ":accomplishments": "loadTab"}
- });
+ this.router = new Router();
+ this.firstRender = true;
+ },
- this.router = new Router();
- this.firstRender = true;
- },
-
- template: _.template(learnerProfileTemplate),
+ template: _.template(learnerProfileTemplate),
- showFullProfile: function () {
- var isAboveMinimumAge = this.options.accountSettingsModel.isAboveMinimumAge();
- if (this.options.ownProfile) {
- return isAboveMinimumAge && this.options.preferencesModel.get('account_privacy') === 'all_users';
- } else {
- return this.options.accountSettingsModel.get('profile_is_public');
- }
- },
+ showFullProfile: function() {
+ var isAboveMinimumAge = this.options.accountSettingsModel.isAboveMinimumAge();
+ if (this.options.ownProfile) {
+ return isAboveMinimumAge && this.options.preferencesModel.get('account_privacy') === 'all_users';
+ } else {
+ return this.options.accountSettingsModel.get('profile_is_public');
+ }
+ },
- setActiveTab: function(tab) {
+ setActiveTab: function(tab) {
// This tab may not actually exist.
- if (this.tabbedView.getTabMeta(tab).tab) {
- this.tabbedView.setActiveTab(tab);
- }
- },
+ if (this.tabbedView.getTabMeta(tab).tab) {
+ this.tabbedView.setActiveTab(tab);
+ }
+ },
- render: function () {
- var self = this;
+ render: function() {
+ var self = this;
- this.sectionTwoView = new SectionTwoTab({
- viewList: this.options.sectionTwoFieldViews,
- showFullProfile: this.showFullProfile,
- ownProfile: this.options.ownProfile
- });
-
- var tabs = [
- {view: this.sectionTwoView, title: gettext("About Me"), url: "about_me"}
- ];
-
- HtmlUtils.setHtml(this.$el, HtmlUtils.template(learnerProfileTemplate)({
- username: self.options.accountSettingsModel.get('username'),
- ownProfile: self.options.ownProfile,
- showFullProfile: self.showFullProfile()
- }));
- this.renderFields();
-
- if (this.showFullProfile() && (this.options.accountSettingsModel.get('accomplishments_shared'))) {
- tabs.push({
- view: this.options.badgeListContainer,
- title: gettext("Accomplishments"),
- url: "accomplishments"
+ this.sectionTwoView = new SectionTwoTab({
+ viewList: this.options.sectionTwoFieldViews,
+ showFullProfile: this.showFullProfile,
+ ownProfile: this.options.ownProfile
});
- this.options.badgeListContainer.collection.fetch().done(function () {
- self.options.badgeListContainer.render();
- }).error(function () {
- self.options.badgeListContainer.renderError();
+
+ var tabs = [
+ {view: this.sectionTwoView, title: gettext('About Me'), url: 'about_me'}
+ ];
+
+ HtmlUtils.setHtml(this.$el, HtmlUtils.template(learnerProfileTemplate)({
+ username: self.options.accountSettingsModel.get('username'),
+ ownProfile: self.options.ownProfile,
+ showFullProfile: self.showFullProfile()
+ }));
+ this.renderFields();
+
+ if (this.showFullProfile() && (this.options.accountSettingsModel.get('accomplishments_shared'))) {
+ tabs.push({
+ view: this.options.badgeListContainer,
+ title: gettext('Accomplishments'),
+ url: 'accomplishments'
+ });
+ this.options.badgeListContainer.collection.fetch().done(function() {
+ self.options.badgeListContainer.render();
+ }).error(function() {
+ self.options.badgeListContainer.renderError();
+ });
+ }
+ this.tabbedView = new TabbedView({
+ tabs: tabs,
+ router: this.router,
+ viewLabel: gettext('Profile')
});
- }
- this.tabbedView = new TabbedView({
- tabs: tabs,
- router: this.router,
- viewLabel: gettext("Profile")
- });
- this.tabbedView.render();
+ this.tabbedView.render();
- if (tabs.length === 1) {
+ if (tabs.length === 1) {
// If the tab is unambiguous, don't display the tab interface.
- this.tabbedView.$el.find('.page-content-nav').hide();
- }
+ this.tabbedView.$el.find('.page-content-nav').hide();
+ }
- this.$el.find('.account-settings-container').append(this.tabbedView.el);
+ this.$el.find('.account-settings-container').append(this.tabbedView.el);
- if (this.firstRender) {
- this.router.on("route:loadTab", _.bind(this.setActiveTab, this));
- Backbone.history.start();
- this.firstRender = false;
+ if (this.firstRender) {
+ this.router.on('route:loadTab', _.bind(this.setActiveTab, this));
+ Backbone.history.start();
+ this.firstRender = false;
// Load from history.
- this.router.navigate((Backbone.history.getFragment() || 'about_me'), {trigger: true});
- } else {
+ this.router.navigate((Backbone.history.getFragment() || 'about_me'), {trigger: true});
+ } else {
// Restart the router so the tab will be brought up anew.
- Backbone.history.stop();
- Backbone.history.start();
+ Backbone.history.stop();
+ Backbone.history.start();
+ }
+
+
+ return this;
+ },
+
+ renderFields: function() {
+ var view = this;
+
+ if (this.options.ownProfile) {
+ var fieldView = this.options.accountPrivacyFieldView,
+ settings = this.options.accountSettingsModel;
+ fieldView.profileIsPrivate = !settings.get('year_of_birth');
+ fieldView.requiresParentalConsent = settings.get('requires_parental_consent');
+ fieldView.isAboveMinimumAge = settings.isAboveMinimumAge();
+ fieldView.undelegateEvents();
+ this.$('.wrapper-profile-field-account-privacy').append(fieldView.render().el);
+ fieldView.delegateEvents();
+ }
+
+ this.$('.profile-section-one-fields').append(this.options.usernameFieldView.render().el);
+
+ var imageView = this.options.profileImageFieldView;
+ this.$('.profile-image-field').append(imageView.render().el);
+
+ if (this.showFullProfile()) {
+ _.each(this.options.sectionOneFieldViews, function(fieldView) {
+ view.$('.profile-section-one-fields').append(fieldView.render().el);
+ });
+ }
+ },
+
+ showLoadingError: function() {
+ this.$('.ui-loading-indicator').addClass('is-hidden');
+ this.$('.ui-loading-error').removeClass('is-hidden');
}
+ });
-
- return this;
- },
-
- renderFields: function() {
- var view = this;
-
- if (this.options.ownProfile) {
- var fieldView = this.options.accountPrivacyFieldView,
- settings = this.options.accountSettingsModel;
- fieldView.profileIsPrivate = !settings.get('year_of_birth');
- fieldView.requiresParentalConsent = settings.get('requires_parental_consent');
- fieldView.isAboveMinimumAge = settings.isAboveMinimumAge();
- fieldView.undelegateEvents();
- this.$('.wrapper-profile-field-account-privacy').append(fieldView.render().el);
- fieldView.delegateEvents();
- }
-
- this.$('.profile-section-one-fields').append(this.options.usernameFieldView.render().el);
-
- var imageView = this.options.profileImageFieldView;
- this.$('.profile-image-field').append(imageView.render().el);
-
- if (this.showFullProfile()) {
- _.each(this.options.sectionOneFieldViews, function (fieldView) {
- view.$('.profile-section-one-fields').append(fieldView.render().el);
- });
-
- }
- },
-
- showLoadingError: function () {
- this.$('.ui-loading-indicator').addClass('is-hidden');
- this.$('.ui-loading-error').removeClass('is-hidden');
- }
+ return LearnerProfileView;
});
-
- return LearnerProfileView;
- });
}).call(this, define || RequireJS.define);
diff --git a/lms/static/js/student_profile/views/section_two_tab.js b/lms/static/js/student_profile/views/section_two_tab.js
index 46c832e068..69d3117320 100644
--- a/lms/static/js/student_profile/views/section_two_tab.js
+++ b/lms/static/js/student_profile/views/section_two_tab.js
@@ -1,18 +1,17 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
- 'gettext', 'jquery', 'underscore', 'backbone', 'text!templates/student_profile/section_two.underscore'],
- function (gettext, $, _, Backbone, sectionTwoTemplate) {
-
+ 'gettext', 'jquery', 'underscore', 'backbone', 'text!templates/student_profile/section_two.underscore'],
+ function(gettext, $, _, Backbone, sectionTwoTemplate) {
var SectionTwoTab = Backbone.View.extend({
attributes: {
'class': 'wrapper-profile-section-two'
},
template: _.template(sectionTwoTemplate),
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
},
- render: function () {
+ render: function() {
var self = this;
var showFullProfile = this.options.showFullProfile();
this.$el.html(this.template({
@@ -20,7 +19,7 @@
showFullProfile: showFullProfile
}));
if (showFullProfile) {
- _.each(this.options.viewList, function (fieldView) {
+ _.each(this.options.viewList, function(fieldView) {
self.$el.find('.field-container').append(fieldView.render().el);
});
}
diff --git a/lms/static/js/student_profile/views/share_modal_view.js b/lms/static/js/student_profile/views/share_modal_view.js
index 00d7235b05..1d77997c60 100644
--- a/lms/static/js/student_profile/views/share_modal_view.js
+++ b/lms/static/js/student_profile/views/share_modal_view.js
@@ -1,37 +1,36 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'moment',
'text!templates/student_profile/share_modal.underscore'],
- function (gettext, $, _, Backbone, Moment, badgeModalTemplate) {
-
+ function(gettext, $, _, Backbone, Moment, badgeModalTemplate) {
var ShareModalView = Backbone.View.extend({
attributes: {
'class': 'badges-overlay'
},
template: _.template(badgeModalTemplate),
events: {
- 'click .badges-modal': function (event) {event.stopPropagation();},
+ 'click .badges-modal': function(event) { event.stopPropagation(); },
'click .badges-modal .close': 'close',
'click .badges-overlay': 'close',
'keydown': 'keyAction',
'focus .focusguard-start': 'focusGuardStart',
'focus .focusguard-end': 'focusGuardEnd'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
},
- focusGuardStart: function () {
+ focusGuardStart: function() {
// Should only be selected directly if shift-tabbing from the start, so grab last item.
- this.$el.find("a").last().focus();
+ this.$el.find('a').last().focus();
},
focusGuardEnd: function() {
- this.$el.find(".badges-modal").focus();
+ this.$el.find('.badges-modal').focus();
},
- close: function () {
+ close: function() {
this.$el.fadeOut('short', 'swing', _.bind(this.remove, this));
this.options.shareButton.focus();
},
- keyAction: function (event) {
+ keyAction: function(event) {
if (event.keyCode === $.ui.keyCode.ESCAPE) {
this.close();
}
@@ -41,7 +40,7 @@
// to its positioning.
this.$el.find('.badges-modal').focus();
},
- render: function () {
+ render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
diff --git a/lms/static/js/toggle_login_modal.js b/lms/static/js/toggle_login_modal.js
index e8310716e3..9485801a7c 100644
--- a/lms/static/js/toggle_login_modal.js
+++ b/lms/static/js/toggle_login_modal.js
@@ -1,5 +1,5 @@
-(function($){
- $.fn.extend({
+(function($) {
+ $.fn.extend({
/*
* leanModal prepares an element to be a modal dialog. Call it once on the
* element that launches the dialog, when the page is ready. This function
@@ -10,117 +10,116 @@
* - have an href= attribute identifying the id of the dialog element,
* - have rel='leanModal'.
*/
- leanModal: function(options) {
- var defaults = {
- top: 100,
- overlay: 0.5,
- closeButton: null,
- position: 'fixed'
- }
+ leanModal: function(options) {
+ var defaults = {
+ top: 100,
+ overlay: 0.5,
+ closeButton: null,
+ position: 'fixed'
+ };
- if ($("#lean_overlay").length == 0) {
- var overlay = $("");
- $("body").append(overlay);
- }
+ if ($('#lean_overlay').length == 0) {
+ var overlay = $("");
+ $('body').append(overlay);
+ }
- options = $.extend(defaults, options);
+ options = $.extend(defaults, options);
- return this.each(function() {
- var o = options;
+ return this.each(function() {
+ var o = options;
- $(this).click(function(e) {
+ $(this).click(function(e) {
+ $('.modal').hide();
- $(".modal").hide();
+ var modal_id = $(this).attr('href');
- var modal_id = $(this).attr("href");
+ if ($(modal_id).hasClass('video-modal')) {
+ // Video modals need to be cloned before being presented as a modal
+ // This is because actions on the video get recorded in the history.
+ // Deleting the video (clone) prevents the odd back button behavior.
+ var modal_clone = $(modal_id).clone(true, true);
+ modal_clone.attr('id', 'modal_clone');
+ $(modal_id).after(modal_clone);
+ modal_id = '#modal_clone';
+ }
- if ($(modal_id).hasClass("video-modal")) {
- //Video modals need to be cloned before being presented as a modal
- //This is because actions on the video get recorded in the history.
- //Deleting the video (clone) prevents the odd back button behavior.
- var modal_clone = $(modal_id).clone(true, true);
- modal_clone.attr('id', 'modal_clone');
- $(modal_id).after(modal_clone);
- modal_id = '#modal_clone';
- }
+ $('#lean_overlay').click(function(e) {
+ close_modal(modal_id, e);
+ });
- $("#lean_overlay").click(function(e) {
- close_modal(modal_id, e);
- });
-
- $(o.closeButton).click(function(e) {
- close_modal(modal_id, e);
- });
+ $(o.closeButton).click(function(e) {
+ close_modal(modal_id, e);
+ });
// To enable closing of email modal when copy button hit
- $(o.copyEmailButton).click(function(e) {
- close_modal(modal_id, e);
- });
+ $(o.copyEmailButton).click(function(e) {
+ close_modal(modal_id, e);
+ });
- var modal_height = $(modal_id).outerHeight();
- var modal_width = $(modal_id).outerWidth();
+ var modal_height = $(modal_id).outerHeight();
+ var modal_width = $(modal_id).outerWidth();
- $('#lean_overlay').css({ 'display' : 'block', opacity : 0 });
- $('#lean_overlay').fadeTo(200,o.overlay);
+ $('#lean_overlay').css({'display': 'block', opacity: 0});
+ $('#lean_overlay').fadeTo(200, o.overlay);
- $('iframe', modal_id).attr('src', $('iframe', modal_id).data('src'));
- if ($(modal_id).hasClass("email-modal")){
- $(modal_id).css({
- 'width' : 80 + '%',
- 'height' : 80 + '%',
- 'position' : o.position,
- 'opacity' : 0,
- 'z-index' : 11000,
- 'left' : 10 + '%',
- 'top' : 10 + '%'
- })
- } else {
- $(modal_id).css({
- 'position' : o.position,
- 'opacity' : 0,
- 'z-index': 11000,
- 'left' : 50 + '%',
- 'margin-left' : -(modal_width/2) + "px",
- 'top' : o.top + "px"
- })
- }
+ $('iframe', modal_id).attr('src', $('iframe', modal_id).data('src'));
+ if ($(modal_id).hasClass('email-modal')) {
+ $(modal_id).css({
+ 'width': 80 + '%',
+ 'height': 80 + '%',
+ 'position': o.position,
+ 'opacity': 0,
+ 'z-index': 11000,
+ 'left': 10 + '%',
+ 'top': 10 + '%'
+ });
+ } else {
+ $(modal_id).css({
+ 'position': o.position,
+ 'opacity': 0,
+ 'z-index': 11000,
+ 'left': 50 + '%',
+ 'margin-left': -(modal_width / 2) + 'px',
+ 'top': o.top + 'px'
+ });
+ }
- $(modal_id).show().fadeTo(200,1);
- $(modal_id).find(".notice").hide().html("");
- var notice = $(this).data('notice')
- if(notice !== undefined) {
- $notice = $(modal_id).find(".notice");
- $notice.show().html(notice);
+ $(modal_id).show().fadeTo(200, 1);
+ $(modal_id).find('.notice').hide().html('');
+ var notice = $(this).data('notice');
+ if (notice !== undefined) {
+ $notice = $(modal_id).find('.notice');
+ $notice.show().html(notice);
// This is for activating leanModal links that were in the notice. We should have a cleaner way of
// allowing all dynamically added leanmodal links to work.
- $notice.find("a[rel*=leanModal]").leanModal({ top : 120, overlay: 1, closeButton: ".close-modal", position: 'absolute' });
- }
- window.scrollTo(0, 0);
- e.preventDefault();
- });
- });
+ $notice.find('a[rel*=leanModal]').leanModal({top: 120, overlay: 1, closeButton: '.close-modal', position: 'absolute'});
+ }
+ window.scrollTo(0, 0);
+ e.preventDefault();
+ });
+ });
- function close_modal(modal_id, e) {
- $("#lean_overlay").fadeOut(200);
- $('iframe', modal_id).attr('src', '');
- $(modal_id).css({ 'display' : 'none' });
- if (modal_id == '#modal_clone') {
- $(modal_id).remove();
+ function close_modal(modal_id, e) {
+ $('#lean_overlay').fadeOut(200);
+ $('iframe', modal_id).attr('src', '');
+ $(modal_id).css({'display': 'none'});
+ if (modal_id == '#modal_clone') {
+ $(modal_id).remove();
+ }
+ e.preventDefault();
+ }
}
- e.preventDefault();
- }
- }
- });
-
- $(document).ready(function ($) {
- $("a[rel*=leanModal]").each(function () {
- $(this).leanModal({ top : 120, overlay: 1, closeButton: ".close-modal", position: 'absolute' });
- embed = $($(this).attr('href')).find('iframe')
- if (embed.length > 0 && embed.attr('src')) {
- var sep = (embed.attr('src').indexOf("?") > 0) ? '&' : '?';
- embed.data('src', embed.attr('src') + sep + 'autoplay=1&rel=0');
- embed.attr('src', '');
- }
});
- });
+
+ $(document).ready(function($) {
+ $('a[rel*=leanModal]').each(function() {
+ $(this).leanModal({top: 120, overlay: 1, closeButton: '.close-modal', position: 'absolute'});
+ embed = $($(this).attr('href')).find('iframe');
+ if (embed.length > 0 && embed.attr('src')) {
+ var sep = (embed.attr('src').indexOf('?') > 0) ? '&' : '?';
+ embed.data('src', embed.attr('src') + sep + 'autoplay=1&rel=0');
+ embed.attr('src', '');
+ }
+ });
+ });
})(jQuery);
diff --git a/lms/static/js/utils/facebook.js b/lms/static/js/utils/facebook.js
index 74b1c2a2d1..d5b8695be0 100644
--- a/lms/static/js/utils/facebook.js
+++ b/lms/static/js/utils/facebook.js
@@ -2,24 +2,24 @@ var FaceBook = (function() {
var _args = {};
return {
- init : function (Args) {
+ init: function(Args) {
_args = Args;
window.fbAsyncInit = function() {
FB.init({
- appId : _args.facebook_app_id,
- xfbml : true,
- version : 'v2.3'
+ appId: _args.facebook_app_id,
+ xfbml: true,
+ version: 'v2.3'
});
};
- (function(d, s, id){
+ (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
- if (d.getElementById(id)) {return;}
+ if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
- js.src = "//connect.facebook.net/en_US/sdk.js";
+ js.src = '//connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
},
- share: function (feed_data) {
+ share: function(feed_data) {
FB.ui({
method: 'feed',
name: feed_data['share_text'],
diff --git a/lms/static/js/utils/navigation.js b/lms/static/js/utils/navigation.js
index 9f46907d0a..fe6d2ba03b 100644
--- a/lms/static/js/utils/navigation.js
+++ b/lms/static/js/utils/navigation.js
@@ -1,7 +1,6 @@
var edx = edx || {},
Navigation = (function() {
-
var navigation = {
init: function() {
@@ -122,9 +121,8 @@ var edx = edx || {},
return {
init: navigation.init
};
-
})();
- edx.util = edx.util || {};
- edx.util.navigation = Navigation;
- edx.util.navigation.init();
+edx.util = edx.util || {};
+edx.util.navigation = Navigation;
+edx.util.navigation.init();
diff --git a/lms/static/js/verify_student/incourse_reverify.js b/lms/static/js/verify_student/incourse_reverify.js
index cad681e848..311c8208e3 100644
--- a/lms/static/js/verify_student/incourse_reverify.js
+++ b/lms/static/js/verify_student/incourse_reverify.js
@@ -7,22 +7,21 @@
*/
var edx = edx || {};
- (function( $, _ ) {
- 'use strict';
- var errorView,
- el = $('#incourse-reverify-container');
+ (function($, _) {
+ 'use strict';
+ var errorView,
+ el = $('#incourse-reverify-container');
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- errorView = new edx.verify_student.ErrorView({
- el: $('#error-container')
- });
+ errorView = new edx.verify_student.ErrorView({
+ el: $('#error-container')
+ });
- return new edx.verify_student.InCourseReverifyView({
- courseKey: el.data('course-key'),
- platformName: el.data('platform-name'),
- usageId: el.data('usage-id'),
- errorModel: errorView.model
- }).render();
-
- })( jQuery, _ );
+ return new edx.verify_student.InCourseReverifyView({
+ courseKey: el.data('course-key'),
+ platformName: el.data('platform-name'),
+ usageId: el.data('usage-id'),
+ errorModel: errorView.model
+ }).render();
+ })(jQuery, _);
diff --git a/lms/static/js/verify_student/models/verification_model.js b/lms/static/js/verify_student/models/verification_model.js
index afe9763564..f5fe173aba 100644
--- a/lms/static/js/verify_student/models/verification_model.js
+++ b/lms/static/js/verify_student/models/verification_model.js
@@ -8,78 +8,77 @@
*/
var edx = edx || {};
- (function( $, Backbone ) {
- 'use strict';
+ (function($, Backbone) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.VerificationModel = Backbone.Model.extend({
+ edx.verify_student.VerificationModel = Backbone.Model.extend({
- defaults: {
+ defaults: {
// If provided, change the user's full name when submitting photos.
- fullName: null,
+ fullName: null,
// Image data for the user's face photo.
- faceImage: "",
+ faceImage: '',
// Image data for the user's ID photo.
// In the case of an in-course reverification, we won't
// need to send this because we'll send the ID photo that
// the user submitted with the initial verification attempt.
- identificationImage: null,
+ identificationImage: null,
// If the verification attempt is associated with a checkpoint
// in a course, we send the the course and checkpoint location.
- courseKey: null,
- checkpoint: null,
- },
+ courseKey: null,
+ checkpoint: null
+ },
- sync: function( method, model ) {
- var headers = { 'X-CSRFToken': $.cookie( 'csrftoken' ) },
- data = {};
+ sync: function(method, model) {
+ var headers = {'X-CSRFToken': $.cookie('csrftoken')},
+ data = {};
- data.face_image = model.get("faceImage");
+ data.face_image = model.get('faceImage');
// The ID photo is optional, since in-course reverification
// re-uses the image from the initial verification attempt.
- if (model.has("identificationImage")) {
- data.photo_id_image = model.get("identificationImage");
- }
+ if (model.has('identificationImage')) {
+ data.photo_id_image = model.get('identificationImage');
+ }
// Full name is an optional parameter; if not provided,
// it won't be changed.
- if (model.has("fullName")) {
- data.full_name = model.get("fullName");
+ if (model.has('fullName')) {
+ data.full_name = model.get('fullName');
// Track the user's decision to change the name on their account
- window.analytics.track( 'edx.bi.user.full_name.changed', {
- category: 'verification'
- });
- }
+ window.analytics.track('edx.bi.user.full_name.changed', {
+ category: 'verification'
+ });
+ }
// If the user entered the verification flow from a checkpoint
// in a course, we need to send the course and checkpoint
// location to associate the attempt with the checkpoint.
- if (model.has("courseKey") && model.has("checkpoint")) {
- data.course_key = model.get("courseKey");
- data.checkpoint = model.get("checkpoint");
- }
+ if (model.has('courseKey') && model.has('checkpoint')) {
+ data.course_key = model.get('courseKey');
+ data.checkpoint = model.get('checkpoint');
+ }
// Submit the request to the server,
// triggering events on success and error.
- $.ajax({
- url: '/verify_student/submit-photos/',
- type: 'POST',
- data: data,
- headers: headers,
- success: function( response ) {
- model.trigger( 'sync', response.url );
- },
- error: function( error ) {
- model.trigger( 'error', error );
- }
- });
- }
- });
-
- })( jQuery, Backbone );
+ $.ajax({
+ url: '/verify_student/submit-photos/',
+ type: 'POST',
+ data: data,
+ headers: headers,
+ success: function(response) {
+ model.trigger('sync', response.url);
+ },
+ error: function(error) {
+ model.trigger('error', error);
+ }
+ });
+ }
+ });
+ })(jQuery, Backbone);
diff --git a/lms/static/js/verify_student/pay_and_verify.js b/lms/static/js/verify_student/pay_and_verify.js
index 440337c4af..19b97b23de 100644
--- a/lms/static/js/verify_student/pay_and_verify.js
+++ b/lms/static/js/verify_student/pay_and_verify.js
@@ -10,7 +10,7 @@
*/
var edx = edx || {};
-(function( $, _ ) {
+(function($, _) {
'use strict';
var errorView,
el = $('#pay-and-verify-container');
@@ -52,15 +52,15 @@ var edx = edx || {};
userEmail: el.data('user-email'),
hasVisibleReqs: _.some(
el.data('requirements'),
- function( isVisible ) { return isVisible; }
+ function(isVisible) { return isVisible; }
),
upgrade: el.data('msg-key') === 'upgrade',
minPrice: el.data('course-mode-min-price'),
sku: el.data('course-mode-sku'),
contributionAmount: el.data('contribution-amount'),
suggestedPrices: _.filter(
- (el.data('course-mode-suggested-prices').toString()).split(","),
- function( price ) { return Boolean( price ); }
+ (el.data('course-mode-suggested-prices').toString()).split(','),
+ function(price) { return Boolean(price); }
),
currency: el.data('course-mode-currency'),
processors: el.data('processors'),
@@ -68,7 +68,7 @@ var edx = edx || {};
courseModeSlug: el.data('course-mode-slug'),
alreadyVerified: el.data('already-verified'),
verificationGoodUntil: el.data('verification-good-until'),
- isABTesting: el.data('is-ab-testing')
+ isABTesting: el.data('is-ab-testing')
},
'payment-confirmation-step': {
courseKey: el.data('course-key'),
@@ -98,4 +98,4 @@ var edx = edx || {};
}
}
}).render();
-})( jQuery, _ );
+})(jQuery, _);
diff --git a/lms/static/js/verify_student/reverify.js b/lms/static/js/verify_student/reverify.js
index 42d732ae2b..12eb641c4c 100644
--- a/lms/static/js/verify_student/reverify.js
+++ b/lms/static/js/verify_student/reverify.js
@@ -7,38 +7,38 @@
*/
var edx = edx || {};
- (function( $, _ ) {
- 'use strict';
- var errorView,
- el = $('#reverify-container');
+ (function($, _) {
+ 'use strict';
+ var errorView,
+ el = $('#reverify-container');
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
// Initialize an error view for displaying top-level error messages.
- errorView = new edx.verify_student.ErrorView({
- el: $('#error-container')
- });
+ errorView = new edx.verify_student.ErrorView({
+ el: $('#error-container')
+ });
// Initialize the base view, passing in information
// from the data attributes on the parent div.
- return new edx.verify_student.ReverifyView({
- errorModel: errorView.model,
- stepInfo: {
- 'face-photo-step': {
- platformName: el.data('platform-name'),
- captureSoundPath: el.data('capture-sound')
- },
- 'id-photo-step': {
- platformName: el.data('platform-name'),
- captureSoundPath: el.data('capture-sound')
- },
- 'review-photos-step': {
- fullName: el.data('full-name'),
- platformName: el.data('platform-name')
- },
- 'reverify-success-step': {
- platformName: el.data('platform-name')
- }
- }
- }).render();
-})( jQuery, _ );
+ return new edx.verify_student.ReverifyView({
+ errorModel: errorView.model,
+ stepInfo: {
+ 'face-photo-step': {
+ platformName: el.data('platform-name'),
+ captureSoundPath: el.data('capture-sound')
+ },
+ 'id-photo-step': {
+ platformName: el.data('platform-name'),
+ captureSoundPath: el.data('capture-sound')
+ },
+ 'review-photos-step': {
+ fullName: el.data('full-name'),
+ platformName: el.data('platform-name')
+ },
+ 'reverify-success-step': {
+ platformName: el.data('platform-name')
+ }
+ }
+ }).render();
+ })(jQuery, _);
diff --git a/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js b/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js
index f9402f56f2..e71976b765 100644
--- a/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js
+++ b/lms/static/js/verify_student/views/enrollment_confirmation_step_view.js
@@ -17,7 +17,7 @@ var edx = edx || {};
postRender: function() {
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
},
defaultContext: function() {
@@ -29,5 +29,4 @@ var edx = edx || {};
};
}
});
-
})();
diff --git a/lms/static/js/verify_student/views/error_view.js b/lms/static/js/verify_student/views/error_view.js
index 67f385a14f..703655260d 100644
--- a/lms/static/js/verify_student/views/error_view.js
+++ b/lms/static/js/verify_student/views/error_view.js
@@ -3,41 +3,40 @@
*/
var edx = edx || {};
-(function ( $, _, Backbone ) {
- 'use strict';
+ (function($, _, Backbone) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.ErrorView = Backbone.View.extend({
+ edx.verify_student.ErrorView = Backbone.View.extend({
- initialize: function( obj ) {
- var ErrorModel = Backbone.Model.extend({});
- this.model = obj.model || new ErrorModel({
- errorTitle: "",
- errorMsg: "",
- shown: false
- });
- this.listenTo( this.model, 'change', this.render );
- },
+ initialize: function(obj) {
+ var ErrorModel = Backbone.Model.extend({});
+ this.model = obj.model || new ErrorModel({
+ errorTitle: '',
+ errorMsg: '',
+ shown: false
+ });
+ this.listenTo(this.model, 'change', this.render);
+ },
- render: function() {
- var renderedHtml = _.template($( '#error-tpl' ).html())(
- {
- errorTitle: this.model.get( 'errorTitle' ),
- errorMsg: this.model.get( 'errorMsg' )
- }
+ render: function() {
+ var renderedHtml = _.template($('#error-tpl').html())(
+ {
+ errorTitle: this.model.get('errorTitle'),
+ errorMsg: this.model.get('errorMsg')
+ }
);
- $( this.el ).html( renderedHtml );
+ $(this.el).html(renderedHtml);
- if ( this.model.get( 'shown' ) ) {
- $( this.el ).show();
- $( "html, body" ).animate({ scrollTop: 0 });
- }
- else {
- $( this.el ).hide();
- }
- }
- });
-
-})( $, _, Backbone );
+ if (this.model.get('shown')) {
+ $(this.el).show();
+ $('html, body').animate({scrollTop: 0});
+ }
+ else {
+ $(this.el).hide();
+ }
+ }
+ });
+ })($, _, Backbone);
diff --git a/lms/static/js/verify_student/views/face_photo_step_view.js b/lms/static/js/verify_student/views/face_photo_step_view.js
index b2654271b2..f9afacb5e5 100644
--- a/lms/static/js/verify_student/views/face_photo_step_view.js
+++ b/lms/static/js/verify_student/views/face_photo_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $ ) {
+(function($) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.FacePhotoStepView = edx.verify_student.StepView.extend({
- templateName: "face_photo_step",
+ templateName: 'face_photo_step',
defaultContext: function() {
return {
@@ -20,7 +20,7 @@ var edx = edx || {};
postRender: function() {
var webcam = edx.verify_student.getSupportedWebcamView({
- el: $( '#facecam' ),
+ el: $('#facecam'),
model: this.model,
modelAttribute: 'faceImage',
submitButton: '#next_step_button',
@@ -29,17 +29,16 @@ var edx = edx || {};
}).render();
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
- this.listenTo( webcam, 'imageCaptured', function() {
+ this.listenTo(webcam, 'imageCaptured', function() {
// Track the user's successful image capture
- window.analytics.track( 'edx.bi.user.face_image.captured', {
+ window.analytics.track('edx.bi.user.face_image.captured', {
category: 'verification'
});
});
- $( '#next_step_button' ).on( 'click', _.bind( this.nextStep, this ) );
- },
+ $('#next_step_button').on('click', _.bind(this.nextStep, this));
+ }
});
-
-})( jQuery );
+})(jQuery);
diff --git a/lms/static/js/verify_student/views/id_photo_step_view.js b/lms/static/js/verify_student/views/id_photo_step_view.js
index f89bd3e7ca..aa8ae4a94b 100644
--- a/lms/static/js/verify_student/views/id_photo_step_view.js
+++ b/lms/static/js/verify_student/views/id_photo_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $ ) {
+(function($) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.IDPhotoStepView = edx.verify_student.StepView.extend({
- templateName: "id_photo_step",
+ templateName: 'id_photo_step',
defaultContext: function() {
return {
@@ -20,7 +20,7 @@ var edx = edx || {};
postRender: function() {
var webcam = edx.verify_student.getSupportedWebcamView({
- el: $( '#idcam' ),
+ el: $('#idcam'),
model: this.model,
modelAttribute: 'identificationImage',
submitButton: '#next_step_button',
@@ -29,17 +29,16 @@ var edx = edx || {};
}).render();
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
- this.listenTo( webcam, 'imageCaptured', function() {
+ this.listenTo(webcam, 'imageCaptured', function() {
// Track the user's successful image capture
- window.analytics.track( 'edx.bi.user.identification_image.captured', {
+ window.analytics.track('edx.bi.user.identification_image.captured', {
category: 'verification'
});
});
- $( '#next_step_button' ).on( 'click', _.bind( this.nextStep, this ) );
+ $('#next_step_button').on('click', _.bind(this.nextStep, this));
}
});
-
-})( jQuery );
+})(jQuery);
diff --git a/lms/static/js/verify_student/views/image_input_view.js b/lms/static/js/verify_student/views/image_input_view.js
index 3b0ef721b2..80b679d143 100644
--- a/lms/static/js/verify_student/views/image_input_view.js
+++ b/lms/static/js/verify_student/views/image_input_view.js
@@ -8,105 +8,104 @@
var edx = edx || {};
- (function( $, _, Backbone, gettext ) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.ImageInputView = Backbone.View.extend({
+ edx.verify_student.ImageInputView = Backbone.View.extend({
- template: '#image_input-tpl',
+ template: '#image_input-tpl',
- initialize: function( obj ) {
- this.$submitButton = obj.submitButton ? $( obj.submitButton ) : '';
- this.modelAttribute = obj.modelAttribute || '';
- this.errorModel = obj.errorModel || null;
- },
+ initialize: function(obj) {
+ this.$submitButton = obj.submitButton ? $(obj.submitButton) : '';
+ this.modelAttribute = obj.modelAttribute || '';
+ this.errorModel = obj.errorModel || null;
+ },
- render: function() {
- var renderedHtml = _.template( $( this.template ).html())({});
- $( this.el ).html( renderedHtml );
+ render: function() {
+ var renderedHtml = _.template($(this.template).html())({});
+ $(this.el).html(renderedHtml);
// Set the submit button to disabled by default
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
- this.$input = $( 'input.image-upload' );
- this.$preview = $( 'img.preview' );
- this.$input.on('change', _.bind( this.handleInputChange, this ) );
+ this.$input = $('input.image-upload');
+ this.$preview = $('img.preview');
+ this.$input.on('change', _.bind(this.handleInputChange, this));
// Initially hide the preview
- this.displayImage( false );
+ this.displayImage(false);
- return this;
- },
+ return this;
+ },
- handleInputChange: function( event ) {
- var files = event.target.files,
- reader = new FileReader();
- if ( files[0] && files[0].type.match( 'image.[png|jpg|jpeg]' ) ) {
- reader.onload = _.bind( this.handleImageUpload, this );
- reader.onerror = _.bind( this.handleUploadError, this );
- reader.readAsDataURL( files[0] );
- } else if ( files.length === 0 ) {
- this.handleUploadError( false );
- } else {
- this.handleUploadError( true );
- }
- },
+ handleInputChange: function(event) {
+ var files = event.target.files,
+ reader = new FileReader();
+ if (files[0] && files[0].type.match('image.[png|jpg|jpeg]')) {
+ reader.onload = _.bind(this.handleImageUpload, this);
+ reader.onerror = _.bind(this.handleUploadError, this);
+ reader.readAsDataURL(files[0]);
+ } else if (files.length === 0) {
+ this.handleUploadError(false);
+ } else {
+ this.handleUploadError(true);
+ }
+ },
- handleImageUpload: function( event ) {
- var imageData = event.target.result;
- this.model.set( this.modelAttribute, imageData );
- this.displayImage( imageData );
- this.setSubmitButtonEnabled( true );
+ handleImageUpload: function(event) {
+ var imageData = event.target.result;
+ this.model.set(this.modelAttribute, imageData);
+ this.displayImage(imageData);
+ this.setSubmitButtonEnabled(true);
// Hide any errors we may have displayed previously
- if ( this.errorModel ) {
- this.errorModel.set({ shown: false });
- }
+ if (this.errorModel) {
+ this.errorModel.set({shown: false});
+ }
- this.trigger( 'imageCaptured' );
- },
+ this.trigger('imageCaptured');
+ },
- displayImage: function( imageData ) {
- if ( imageData ) {
- this.$preview
- .attr( 'src', imageData )
+ displayImage: function(imageData) {
+ if (imageData) {
+ this.$preview
+ .attr('src', imageData)
.removeClass('is-hidden')
.attr('aria-hidden', 'false');
- } else {
- this.$preview
- .attr( 'src', '' )
+ } else {
+ this.$preview
+ .attr('src', '')
.addClass('is-hidden')
.attr('aria-hidden', 'true');
- }
- },
+ }
+ },
- handleUploadError: function( displayError ) {
- this.displayImage( null );
- this.setSubmitButtonEnabled( false );
- if ( this.errorModel ) {
- if ( displayError ) {
- this.errorModel.set({
- errorTitle: gettext( 'Image Upload Error' ),
- errorMsg: gettext( 'Please verify that you have uploaded a valid image (PNG and JPEG).' ),
- shown: true
- });
- } else {
- this.errorModel.set({
- shown: false
- });
- }
- }
- this.trigger( 'error' );
- },
+ handleUploadError: function(displayError) {
+ this.displayImage(null);
+ this.setSubmitButtonEnabled(false);
+ if (this.errorModel) {
+ if (displayError) {
+ this.errorModel.set({
+ errorTitle: gettext('Image Upload Error'),
+ errorMsg: gettext('Please verify that you have uploaded a valid image (PNG and JPEG).'),
+ shown: true
+ });
+ } else {
+ this.errorModel.set({
+ shown: false
+ });
+ }
+ }
+ this.trigger('error');
+ },
- setSubmitButtonEnabled: function( isEnabled ) {
- this.$submitButton
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ setSubmitButtonEnabled: function(isEnabled) {
+ this.$submitButton
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
- }
- });
-
- })( jQuery, _, Backbone, gettext );
+ }
+ });
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/incourse_reverify_view.js b/lms/static/js/verify_student/views/incourse_reverify_view.js
index 1587f44aef..bbcaec2b19 100644
--- a/lms/static/js/verify_student/views/incourse_reverify_view.js
+++ b/lms/static/js/verify_student/views/incourse_reverify_view.js
@@ -6,43 +6,43 @@
*/
var edx = edx || {};
- (function( $, _, _s, Backbone, gettext, HtmlUtils ) {
- 'use strict';
+ (function($, _, _s, Backbone, gettext, HtmlUtils) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.InCourseReverifyView = Backbone.View.extend({
+ edx.verify_student.InCourseReverifyView = Backbone.View.extend({
- el: '#incourse-reverify-container',
- templateId: '#incourse_reverify-tpl',
- submitButtonId: '#submit',
+ el: '#incourse-reverify-container',
+ templateId: '#incourse_reverify-tpl',
+ submitButtonId: '#submit',
- events: {
- 'click #submit': 'submitPhoto'
- },
+ events: {
+ 'click #submit': 'submitPhoto'
+ },
- initialize: function( obj ) {
- _.mixin( _s.exports() );
+ initialize: function(obj) {
+ _.mixin(_s.exports());
- this.errorModel = obj.errorModel || null;
- this.courseKey = obj.courseKey || null;
- this.platformName = obj.platformName || null;
- this.usageId = obj.usageId || null;
+ this.errorModel = obj.errorModel || null;
+ this.courseKey = obj.courseKey || null;
+ this.platformName = obj.platformName || null;
+ this.usageId = obj.usageId || null;
- this.model = new edx.verify_student.VerificationModel({
- courseKey: this.courseKey,
- checkpoint: this.usageId
- });
+ this.model = new edx.verify_student.VerificationModel({
+ courseKey: this.courseKey,
+ checkpoint: this.usageId
+ });
- this.listenTo( this.model, 'sync', _.bind( this.handleSubmitPhotoSuccess, this ));
- this.listenTo( this.model, 'error', _.bind( this.handleSubmissionError, this ));
- },
+ this.listenTo(this.model, 'sync', _.bind(this.handleSubmitPhotoSuccess, this));
+ this.listenTo(this.model, 'error', _.bind(this.handleSubmissionError, this));
+ },
- render: function() {
- HtmlUtils.setHtml(
+ render: function() {
+ HtmlUtils.setHtml(
this.el,
- HtmlUtils.template($( this.templateId ).html())(
+ HtmlUtils.template($(this.templateId).html())(
{
courseKey: this.courseKey,
platformName: this.platformName
@@ -53,53 +53,53 @@
// Render the webcam view *after* the parent view
// so that the container div for the webcam
// exists in the DOM.
- this.renderWebcam();
+ this.renderWebcam();
- return this;
- },
+ return this;
+ },
- renderWebcam: function() {
- edx.verify_student.getSupportedWebcamView({
- el: $( '#webcam' ),
- model: this.model,
- modelAttribute: 'faceImage',
- submitButton: this.submitButtonId,
- errorModel: this.errorModel
- }).render();
- },
+ renderWebcam: function() {
+ edx.verify_student.getSupportedWebcamView({
+ el: $('#webcam'),
+ model: this.model,
+ modelAttribute: 'faceImage',
+ submitButton: this.submitButtonId,
+ errorModel: this.errorModel
+ }).render();
+ },
- submitPhoto: function() {
+ submitPhoto: function() {
// disable the submit button to prevent multiple submissions.
- this.setSubmitButtonEnabled(false);
- this.model.save();
- },
+ this.setSubmitButtonEnabled(false);
+ this.model.save();
+ },
- handleSubmitPhotoSuccess: function(redirect_url) {
+ handleSubmitPhotoSuccess: function(redirect_url) {
// Redirect back to the courseware at the checkpoint location
- window.location.href = redirect_url;
- },
+ window.location.href = redirect_url;
+ },
- handleSubmissionError: function(xhr) {
- var errorMsg = gettext( 'An error has occurred. Please try again later.' );
+ handleSubmissionError: function(xhr) {
+ var errorMsg = gettext('An error has occurred. Please try again later.');
// Re-enable the submit button to allow the user to retry
- this.setSubmitButtonEnabled( true );
+ this.setSubmitButtonEnabled(true);
- if ( xhr.status === 400 ) {
- errorMsg = xhr.responseText;
- }
+ if (xhr.status === 400) {
+ errorMsg = xhr.responseText;
+ }
- this.errorModel.set({
- errorTitle: gettext( 'Could not submit photos' ),
- errorMsg: errorMsg,
- shown: true
- });
- },
- setSubmitButtonEnabled: function( isEnabled ) {
- $(this.submitButtonId)
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ this.errorModel.set({
+ errorTitle: gettext('Could not submit photos'),
+ errorMsg: errorMsg,
+ shown: true
+ });
+ },
+ setSubmitButtonEnabled: function(isEnabled) {
+ $(this.submitButtonId)
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
- }
- });
-})(jQuery, _, _.str, Backbone, gettext, edx.HtmlUtils);
+ }
+ });
+ })(jQuery, _, _.str, Backbone, gettext, edx.HtmlUtils);
diff --git a/lms/static/js/verify_student/views/intro_step_view.js b/lms/static/js/verify_student/views/intro_step_view.js
index dd0e75cbc6..5fb9d0bc3d 100644
--- a/lms/static/js/verify_student/views/intro_step_view.js
+++ b/lms/static/js/verify_student/views/intro_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $ ) {
+(function($) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.IntroStepView = edx.verify_student.StepView.extend({
- templateName: "intro_step",
+ templateName: 'intro_step',
defaultContext: function() {
return {
@@ -31,9 +31,8 @@ var edx = edx || {};
// second step.
postRender: function() {
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
}
});
-
-})( jQuery );
+})(jQuery);
diff --git a/lms/static/js/verify_student/views/make_payment_step_view.js b/lms/static/js/verify_student/views/make_payment_step_view.js
index 65019c7adb..3e9eb7e532 100644
--- a/lms/static/js/verify_student/views/make_payment_step_view.js
+++ b/lms/static/js/verify_student/views/make_payment_step_view.js
@@ -3,22 +3,22 @@
*/
var edx = edx || {};
-(function( $, _, gettext, interpolate_text ) {
+(function($, _, gettext, interpolate_text) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.MakePaymentStepView = edx.verify_student.StepView.extend({
- templateName: "make_payment_step",
+ templateName: 'make_payment_step',
btnClass: 'action-primary',
- initialize: function( obj ) {
- _.extend( this, obj );
- if (this.templateContext().isABTesting) {
- this.templateName = 'make_payment_step_ab_testing';
- this.btnClass = 'action-primary-blue';
- }
+ initialize: function(obj) {
+ _.extend(this, obj);
+ if (this.templateContext().isABTesting) {
+ this.templateName = 'make_payment_step_ab_testing';
+ this.btnClass = 'action-primary-blue';
+ }
},
defaultContext: function() {
@@ -42,25 +42,25 @@ var edx = edx || {};
};
},
- _getProductText: function( modeSlug, isUpgrade ) {
- switch ( modeSlug ) {
- case "professional":
- return gettext( "Professional Education Verified Certificate" );
- case "no-id-professional":
- return gettext( "Professional Education" );
- default:
- if ( isUpgrade ) {
- return gettext( "Verified Certificate upgrade" );
- } else {
- return gettext( "Verified Certificate" );
- }
+ _getProductText: function(modeSlug, isUpgrade) {
+ switch (modeSlug) {
+ case 'professional':
+ return gettext('Professional Education Verified Certificate');
+ case 'no-id-professional':
+ return gettext('Professional Education');
+ default:
+ if (isUpgrade) {
+ return gettext('Verified Certificate upgrade');
+ } else {
+ return gettext('Verified Certificate');
+ }
}
},
_getPaymentButtonText: function(processorName) {
- if (processorName.toLowerCase().substr(0, 11)=='cybersource') {
+ if (processorName.toLowerCase().substr(0, 11) == 'cybersource') {
return gettext('Checkout');
- } else if (processorName.toLowerCase()=='paypal') {
+ } else if (processorName.toLowerCase() == 'paypal') {
return gettext('Checkout with PayPal');
} else {
// This is mainly for testing as no other processors are supported right now.
@@ -80,7 +80,7 @@ var edx = edx || {};
var templateContext = this.templateContext(),
hasVisibleReqs = _.some(
templateContext.requirements,
- function( isVisible ) { return isVisible; }
+ function(isVisible) { return isVisible; }
),
// This a hack to appease /lms/static/js/spec/verify_student/pay_and_verify_view_spec.js,
// which does not load an actual template context.
@@ -88,7 +88,7 @@ var edx = edx || {};
self = this;
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'payment', this.templateName );
+ window.analytics.page('payment', this.templateName);
// The contribution section is hidden by default
// Display it if the user hasn't already selected an amount
@@ -98,22 +98,22 @@ var edx = edx || {};
// Otherwise, there's absolutely nothing to do on this page.
// In the future, we'll likely skip directly to payment
// from the track selection page if this happens.
- if ( templateContext.upgrade || !templateContext.contributionAmount || !hasVisibleReqs ) {
- $( '.wrapper-task' ).removeClass( 'hidden' ).removeAttr( 'aria-hidden' );
+ if (templateContext.upgrade || !templateContext.contributionAmount || !hasVisibleReqs) {
+ $('.wrapper-task').removeClass('hidden').removeAttr('aria-hidden');
}
- if ( templateContext.suggestedPrices.length > 0 ) {
+ if (templateContext.suggestedPrices.length > 0) {
// Enable the payment button once an amount is chosen
- $( 'input[name="contribution"]' ).on( 'click', _.bind( this.setPaymentEnabled, this ) );
+ $('input[name="contribution"]').on('click', _.bind(this.setPaymentEnabled, this));
} else {
// If there is only one payment option, then the user isn't shown
// radio buttons, so we need to enable the radio button.
- this.setPaymentEnabled( true );
+ this.setPaymentEnabled(true);
}
// render the name of the product being paid for
- $( 'div.payment-buttons span.product-name').append(
- self._getProductText( templateContext.courseModeSlug, templateContext.upgrade )
+ $('div.payment-buttons span.product-name').append(
+ self._getProductText(templateContext.courseModeSlug, templateContext.upgrade)
);
if (processors.length === 0) {
@@ -122,26 +122,26 @@ var edx = edx || {};
errorTitle: gettext('All payment options are currently unavailable.'),
errorMsg: gettext('Try the transaction again in a few minutes.'),
shown: true
- })
+ });
}
else {
// create a button for each payment processor
_.each(processors.reverse(), function(processorName) {
- $( 'div.payment-buttons' ).append( self._getPaymentButtonHtml(processorName) );
+ $('div.payment-buttons').append(self._getPaymentButtonHtml(processorName));
});
}
// Handle payment submission
- $( '.payment-button' ).on( 'click', _.bind( this.createOrder, this ) );
+ $('.payment-button').on('click', _.bind(this.createOrder, this));
},
- setPaymentEnabled: function( isEnabled ) {
- if ( _.isUndefined( isEnabled ) ) {
+ setPaymentEnabled: function(isEnabled) {
+ if (_.isUndefined(isEnabled)) {
isEnabled = true;
}
- $( '.payment-button' )
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ $('.payment-button')
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
},
@@ -160,9 +160,9 @@ var edx = edx || {};
};
// Disable the payment button to prevent multiple submissions
- this.setPaymentEnabled( false );
+ this.setPaymentEnabled(false);
- $( event.target ).toggleClass( 'is-selected' );
+ $(event.target).toggleClass('is-selected');
// Create the order for the amount
$.ajax({
@@ -176,24 +176,23 @@ var edx = edx || {};
success: this.handleCreateOrderResponse,
error: this.handleCreateOrderError
});
-
},
- handleCreateOrderResponse: function( paymentData ) {
+ handleCreateOrderResponse: function(paymentData) {
// At this point, the basket has been created on the server,
// and we've received signed payment parameters.
// We need to dynamically construct a form using
// these parameters, then submit it to the payment processor.
// This will send the user to an externally-hosted page
// where she can proceed with payment.
- var form = $( '#payment-processor-form' );
+ var form = $('#payment-processor-form');
- $( 'input', form ).remove();
+ $('input', form).remove();
- form.attr( 'action', paymentData.payment_page_url );
- form.attr( 'method', 'POST' );
+ form.attr('action', paymentData.payment_page_url);
+ form.attr('method', 'POST');
- _.each( paymentData.payment_form_data, function( value, key ) {
+ _.each(paymentData.payment_form_data, function(value, key) {
$('').attr({
type: 'hidden',
name: key,
@@ -204,70 +203,70 @@ var edx = edx || {};
// Marketing needs a way to tell the difference between users
// leaving for the payment processor and users dropping off on
// this page. A virtual pageview can be used to do this.
- window.analytics.page( 'payment', 'payment_processor_step' );
+ window.analytics.page('payment', 'payment_processor_step');
- this.submitForm( form );
+ this.submitForm(form);
},
- handleCreateOrderError: function( xhr ) {
- var errorMsg = gettext( 'An error has occurred. Please try again.' );
+ handleCreateOrderError: function(xhr) {
+ var errorMsg = gettext('An error has occurred. Please try again.');
- if ( xhr.status === 400 ) {
+ if (xhr.status === 400) {
errorMsg = xhr.responseText;
}
this.errorModel.set({
- errorTitle: gettext( 'Could not submit order' ),
+ errorTitle: gettext('Could not submit order'),
errorMsg: errorMsg,
shown: true
});
// Re-enable the button so the user can re-try
- this.setPaymentEnabled( true );
+ this.setPaymentEnabled(true);
- $( '.payment-button' ).toggleClass( 'is-selected', false );
+ $('.payment-button').toggleClass('is-selected', false);
},
getPaymentAmount: function() {
- var contributionInput = $( 'input[name="contribution"]:checked' , this.el),
+ var contributionInput = $('input[name="contribution"]:checked', this.el),
amount = null;
- if ( contributionInput.attr('id') === 'contribution-other' ) {
- amount = $( 'input[name="contribution-other-amt"]' , this.el ).val();
+ if (contributionInput.attr('id') === 'contribution-other') {
+ amount = $('input[name="contribution-other-amt"]', this.el).val();
} else {
amount = contributionInput.val();
}
// If no suggested prices are available, then the user does not
// get the option to select a price. Default to the minimum.
- if ( !amount ) {
+ if (!amount) {
amount = this.templateContext().minPrice;
}
return amount;
},
- selectPaymentAmount: function( amount ) {
- var amountFloat = parseFloat( amount ),
+ selectPaymentAmount: function(amount) {
+ var amountFloat = parseFloat(amount),
foundPrice,
sel;
// Check if we have a suggested price that matches the amount
foundPrice = _.find(
this.stepData.suggestedPrices,
- function( price ) {
- return parseFloat( price ) === amountFloat;
+ function(price) {
+ return parseFloat(price) === amountFloat;
}
);
// If we've found an option for the price, select it.
- if ( foundPrice ) {
- sel = _.sprintf( 'input[name="contribution"][value="%s"]', foundPrice );
- $( sel ).prop( 'checked', true );
+ if (foundPrice) {
+ sel = _.sprintf('input[name="contribution"][value="%s"]', foundPrice);
+ $(sel).prop('checked', true);
} else {
// Otherwise, enter the value into the text box
- $( '#contribution-other-amt', this.el ).val( amount );
- $( '#contribution-other', this.el ).prop( 'checked', true );
+ $('#contribution-other-amt', this.el).val(amount);
+ $('#contribution-other', this.el).prop('checked', true);
}
// In either case, enable the payment button
@@ -277,10 +276,9 @@ var edx = edx || {};
},
// Stubbed out in tests
- submitForm: function( form ) {
+ submitForm: function(form) {
form.submit();
}
});
-
-})( jQuery, _, gettext, interpolate_text );
+})(jQuery, _, gettext, interpolate_text);
diff --git a/lms/static/js/verify_student/views/pay_and_verify_view.js b/lms/static/js/verify_student/views/pay_and_verify_view.js
index 5c6239479d..386030598b 100644
--- a/lms/static/js/verify_student/views/pay_and_verify_view.js
+++ b/lms/static/js/verify_student/views/pay_and_verify_view.js
@@ -24,20 +24,20 @@ var edx = edx || {};
'review-photos-step'
],
- initialize: function( obj ) {
+ initialize: function(obj) {
this.errorModel = obj.errorModel || null;
this.displaySteps = obj.displaySteps || [];
this.courseKey = obj.courseKey || null;
this.checkpointLocation = obj.checkpointLocation || null;
- this.initializeStepViews( obj.stepInfo || {} );
+ this.initializeStepViews(obj.stepInfo || {});
this.currentStepIndex = _.indexOf(
- _.pluck( this.displaySteps, 'name' ),
+ _.pluck(this.displaySteps, 'name'),
obj.currentStep
);
},
- initializeStepViews: function( stepInfo ) {
+ initializeStepViews: function(stepInfo) {
var i,
stepName,
stepData,
@@ -73,22 +73,22 @@ var edx = edx || {};
checkpoint: this.checkpointLocation
});
- for ( i = 0; i < this.displaySteps.length; i++ ) {
+ for (i = 0; i < this.displaySteps.length; i++) {
stepName = this.displaySteps[i].name;
subview = null;
- if ( i < this.displaySteps.length - 1) {
+ if (i < this.displaySteps.length - 1) {
nextStepTitle = this.displaySteps[i + 1].title;
} else {
- nextStepTitle = "";
+ nextStepTitle = '';
}
- if ( subviewConstructors.hasOwnProperty( stepName ) ) {
+ if (subviewConstructors.hasOwnProperty(stepName)) {
stepData = {};
// Add any info specific to this step
- if ( stepInfo.hasOwnProperty( stepName ) ) {
- _.extend( stepData, stepInfo[ stepName ] );
+ if (stepInfo.hasOwnProperty(stepName)) {
+ _.extend(stepData, stepInfo[stepName]);
}
subviewConfig = {
@@ -98,19 +98,19 @@ var edx = edx || {};
};
// For photo verification steps, set the shared photo model
- if ( this.VERIFICATION_VIEW_NAMES.indexOf(stepName) >= 0 ) {
- _.extend( subviewConfig, { model: verificationModel } );
+ if (this.VERIFICATION_VIEW_NAMES.indexOf(stepName) >= 0) {
+ _.extend(subviewConfig, {model: verificationModel});
}
// Create the subview instance
// Note that we are NOT yet rendering the view,
// so this doesn't trigger GET requests or modify
// the DOM.
- this.subviews[stepName] = new subviewConstructors[stepName]( subviewConfig );
+ this.subviews[stepName] = new subviewConstructors[stepName](subviewConfig);
// Listen for events to change the current step
- this.listenTo( this.subviews[stepName], 'next-step', this.nextStep );
- this.listenTo( this.subviews[stepName], 'go-to-step', this.goToStep );
+ this.listenTo(this.subviews[stepName], 'next-step', this.nextStep);
+ this.listenTo(this.subviews[stepName], 'go-to-step', this.goToStep);
}
}
},
@@ -124,7 +124,7 @@ var edx = edx || {};
var stepName, stepView, stepEl;
// Get or create the step container
- stepEl = $("#current-step-container");
+ stepEl = $('#current-step-container');
if (!stepEl.length) {
stepEl = $('').appendTo(this.el);
}
@@ -132,8 +132,8 @@ var edx = edx || {};
// Render the subview
// When the view is rendered, it will overwrite the existing
// step in the DOM.
- stepName = this.displaySteps[ this.currentStepIndex ].name;
- stepView = this.subviews[ stepName ];
+ stepName = this.displaySteps[this.currentStepIndex].name;
+ stepView = this.subviews[stepName];
stepView.el = stepEl;
stepView.render();
},
@@ -146,18 +146,17 @@ var edx = edx || {};
this.render();
},
- goToStep: function( stepName ) {
+ goToStep: function(stepName) {
var stepIndex = _.indexOf(
- _.pluck( this.displaySteps, 'name' ),
+ _.pluck(this.displaySteps, 'name'),
stepName
);
- if ( stepIndex >= 0 ) {
+ if (stepIndex >= 0) {
this.currentStepIndex = stepIndex;
}
this.render();
}
});
-
})(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/payment_confirmation_step_view.js b/lms/static/js/verify_student/views/payment_confirmation_step_view.js
index 5e581dc7d7..cba61eebc6 100644
--- a/lms/static/js/verify_student/views/payment_confirmation_step_view.js
+++ b/lms/static/js/verify_student/views/payment_confirmation_step_view.js
@@ -3,14 +3,14 @@
*/
var edx = edx || {};
-(function( $, _, gettext ) {
+(function($, _, gettext) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.PaymentConfirmationStepView = edx.verify_student.StepView.extend({
- templateName: "payment_confirmation_step",
+ templateName: 'payment_confirmation_step',
defaultContext: function() {
return {
@@ -40,19 +40,19 @@ var edx = edx || {};
* @return {object} A JQuery promise that resolves with the modified
* template context.
*/
- updateContext: function( templateContext ) {
+ updateContext: function(templateContext) {
var view = this;
return $.Deferred(
- function( defer ) {
- var paymentOrderNum = $.url( '?payment-order-num' );
- if ( paymentOrderNum ) {
+ function(defer) {
+ var paymentOrderNum = $.url('?payment-order-num');
+ if (paymentOrderNum) {
// If there is a payment order number, try to retrieve
// the receipt information from the shopping cart.
- view.getReceiptData( paymentOrderNum ).done(
- function( data ) {
+ view.getReceiptData(paymentOrderNum).done(
+ function(data) {
// Add the receipt info to the template context
- _.extend( templateContext, { receipt: this.receiptContext( data ) } );
- defer.resolveWith( view, [ templateContext ]);
+ _.extend(templateContext, {receipt: this.receiptContext(data)});
+ defer.resolveWith(view, [templateContext]);
}
).fail(function() {
// Display an error
@@ -61,16 +61,16 @@ var edx = edx || {};
defer.rejectWith(
this,
[
- gettext( "Error" ),
- gettext( "Could not retrieve payment information" )
+ gettext('Error'),
+ gettext('Could not retrieve payment information')
]
);
});
} else {
// If no payment order is provided, return the original context
// The template is responsible for displaying a default state.
- _.extend( templateContext, { receipt: null } );
- defer.resolveWith( view, [ templateContext ]);
+ _.extend(templateContext, {receipt: null});
+ defer.resolveWith(view, [templateContext]);
}
}
).promise();
@@ -87,15 +87,15 @@ var edx = edx || {};
$verifyLaterButton = $('#verify_later_button');
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'payment', this.templateName );
+ window.analytics.page('payment', this.templateName);
// Track the user's decision to verify immediately
- window.analytics.trackLink( $verifyNowButton, 'edx.bi.user.verification.immediate', {
+ window.analytics.trackLink($verifyNowButton, 'edx.bi.user.verification.immediate', {
category: 'verification'
});
// Track the user's decision to defer their verification
- window.analytics.trackLink( $verifyLaterButton, 'edx.bi.user.verification.deferred', {
+ window.analytics.trackLink($verifyLaterButton, 'edx.bi.user.verification.deferred', {
category: 'verification'
});
},
@@ -105,9 +105,9 @@ var edx = edx || {};
* @param {int} paymentOrderNum The order number of the payment.
* @return {object} JQuery Promise.
*/
- getReceiptData: function( paymentOrderNum ) {
+ getReceiptData: function(paymentOrderNum) {
return $.ajax({
- url: _.sprintf( '/shoppingcart/receipt/%s/', paymentOrderNum ),
+ url: _.sprintf('/shoppingcart/receipt/%s/', paymentOrderNum),
type: 'GET',
dataType: 'json',
context: this
@@ -121,7 +121,7 @@ var edx = edx || {};
* @param {object} data Receipt data received from the server
* @return {object} Receipt template context.
*/
- receiptContext: function( data ) {
+ receiptContext: function(data) {
var view = this,
receiptContext;
@@ -129,8 +129,8 @@ var edx = edx || {};
orderNum: data.orderNum,
currency: data.currency,
purchasedDatetime: data.purchase_datetime,
- totalCost: view.formatMoney( data.total_cost ),
- isRefunded: data.status === "refunded",
+ totalCost: view.formatMoney(data.total_cost),
+ isRefunded: data.status === 'refunded',
billedTo: {
firstName: data.billed_to.first_name,
lastName: data.billed_to.last_name,
@@ -144,10 +144,10 @@ var edx = edx || {};
receiptContext.items = _.map(
data.items,
- function( item ) {
+ function(item) {
return {
lineDescription: item.line_desc,
- cost: view.formatMoney( item.line_cost )
+ cost: view.formatMoney(item.line_cost)
};
}
);
@@ -155,9 +155,8 @@ var edx = edx || {};
return receiptContext;
},
- formatMoney: function( moneyStr ) {
- return Number( moneyStr ).toFixed(2);
+ formatMoney: function(moneyStr) {
+ return Number(moneyStr).toFixed(2);
}
});
-
-})( jQuery, _, gettext );
+})(jQuery, _, gettext);
diff --git a/lms/static/js/verify_student/views/reverify_success_step_view.js b/lms/static/js/verify_student/views/reverify_success_step_view.js
index 6d87d12eec..939f3abfac 100644
--- a/lms/static/js/verify_student/views/reverify_success_step_view.js
+++ b/lms/static/js/verify_student/views/reverify_success_step_view.js
@@ -6,12 +6,11 @@
var edx = edx || {};
(function() {
- 'use strict';
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
-
- edx.verify_student.ReverifySuccessStepView = edx.verify_student.StepView.extend({
- templateName: 'reverify_success_step'
- });
+ edx.verify_student = edx.verify_student || {};
+ edx.verify_student.ReverifySuccessStepView = edx.verify_student.StepView.extend({
+ templateName: 'reverify_success_step'
+ });
})();
diff --git a/lms/static/js/verify_student/views/reverify_view.js b/lms/static/js/verify_student/views/reverify_view.js
index 10547cddd9..55d5aabc60 100644
--- a/lms/static/js/verify_student/views/reverify_view.js
+++ b/lms/static/js/verify_student/views/reverify_view.js
@@ -9,107 +9,106 @@
var edx = edx || {};
-(function($, _, Backbone, gettext) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.ReverifyView = Backbone.View.extend({
- el: '#reverify-container',
+ edx.verify_student.ReverifyView = Backbone.View.extend({
+ el: '#reverify-container',
- stepOrder: [
- "face-photo-step",
- "id-photo-step",
- "review-photos-step",
- "reverify-success-step"
- ],
- stepViews: {},
+ stepOrder: [
+ 'face-photo-step',
+ 'id-photo-step',
+ 'review-photos-step',
+ 'reverify-success-step'
+ ],
+ stepViews: {},
- initialize: function( obj ) {
- this.errorModel = obj.errorModel || null;
- this.initializeStepViews( obj.stepInfo || {} );
- this.currentStepIndex = 0;
- },
+ initialize: function(obj) {
+ this.errorModel = obj.errorModel || null;
+ this.initializeStepViews(obj.stepInfo || {});
+ this.currentStepIndex = 0;
+ },
- initializeStepViews: function( stepInfo ) {
- var verificationModel, stepViewConstructors, nextStepTitles;
+ initializeStepViews: function(stepInfo) {
+ var verificationModel, stepViewConstructors, nextStepTitles;
// We need to initialize this here, because
// outside of this method the subview classes
// might not yet have been loaded.
- stepViewConstructors = {
- 'face-photo-step': edx.verify_student.FacePhotoStepView,
- 'id-photo-step': edx.verify_student.IDPhotoStepView,
- 'review-photos-step': edx.verify_student.ReviewPhotosStepView,
- 'reverify-success-step': edx.verify_student.ReverifySuccessStepView
- };
+ stepViewConstructors = {
+ 'face-photo-step': edx.verify_student.FacePhotoStepView,
+ 'id-photo-step': edx.verify_student.IDPhotoStepView,
+ 'review-photos-step': edx.verify_student.ReviewPhotosStepView,
+ 'reverify-success-step': edx.verify_student.ReverifySuccessStepView
+ };
- nextStepTitles = [
- gettext( "Take a photo of your ID" ),
- gettext( "Review your info" ),
- gettext( "Confirm" ),
- ""
- ];
+ nextStepTitles = [
+ gettext('Take a photo of your ID'),
+ gettext('Review your info'),
+ gettext('Confirm'),
+ ''
+ ];
// Create the verification model, which is shared
// among the different steps. This allows
// one step to save photos and another step
// to submit them.
- verificationModel = new edx.verify_student.VerificationModel();
+ verificationModel = new edx.verify_student.VerificationModel();
- _.each(this.stepOrder, function(name, index) {
- var stepView = new stepViewConstructors[name]({
- errorModel: this.errorModel,
- nextStepTitle: nextStepTitles[index],
- stepData: stepInfo[name],
- model: verificationModel
- });
+ _.each(this.stepOrder, function(name, index) {
+ var stepView = new stepViewConstructors[name]({
+ errorModel: this.errorModel,
+ nextStepTitle: nextStepTitles[index],
+ stepData: stepInfo[name],
+ model: verificationModel
+ });
- this.listenTo(stepView, 'next-step', this.nextStep);
- this.listenTo(stepView, 'go-to-step', this.goToStep);
+ this.listenTo(stepView, 'next-step', this.nextStep);
+ this.listenTo(stepView, 'go-to-step', this.goToStep);
- this.stepViews[name] = stepView;
- }, this);
- },
+ this.stepViews[name] = stepView;
+ }, this);
+ },
- render: function() {
- this.renderCurrentStep();
- return this;
- },
+ render: function() {
+ this.renderCurrentStep();
+ return this;
+ },
- renderCurrentStep: function() {
- var stepView, stepEl;
+ renderCurrentStep: function() {
+ var stepView, stepEl;
// Get or create the step container
- stepEl = $("#current-step-container");
- if (!stepEl.length) {
- stepEl = $('').appendTo(this.el);
- }
+ stepEl = $('#current-step-container');
+ if (!stepEl.length) {
+ stepEl = $('').appendTo(this.el);
+ }
// Render the step subview
// When the view is rendered, it will overwrite the existing step in the DOM.
- stepView = this.stepViews[ this.stepOrder[ this.currentStepIndex ] ];
- stepView.el = stepEl;
- stepView.render();
- },
+ stepView = this.stepViews[this.stepOrder[this.currentStepIndex]];
+ stepView.el = stepEl;
+ stepView.render();
+ },
- nextStep: function() {
- this.currentStepIndex = Math.min(
+ nextStep: function() {
+ this.currentStepIndex = Math.min(
this.currentStepIndex + 1,
this.stepOrder.length - 1
);
- this.render();
- },
+ this.render();
+ },
- goToStep: function( stepName ) {
- var stepIndex = _.indexOf(this.stepOrder, stepName);
+ goToStep: function(stepName) {
+ var stepIndex = _.indexOf(this.stepOrder, stepName);
- if ( stepIndex >= 0 ) {
- this.currentStepIndex = stepIndex;
- }
+ if (stepIndex >= 0) {
+ this.currentStepIndex = stepIndex;
+ }
- this.render();
- }
- });
-
-})(jQuery, _, Backbone, gettext);
+ this.render();
+ }
+ });
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/review_photos_step_view.js b/lms/static/js/verify_student/views/review_photos_step_view.js
index a83ed906ee..61cb014a74 100644
--- a/lms/static/js/verify_student/views/review_photos_step_view.js
+++ b/lms/static/js/verify_student/views/review_photos_step_view.js
@@ -3,105 +3,104 @@
*/
var edx = edx || {};
-(function( $, gettext ) {
+(function($, gettext) {
'use strict';
edx.verify_student = edx.verify_student || {};
edx.verify_student.ReviewPhotosStepView = edx.verify_student.StepView.extend({
- templateName: "review_photos_step",
+ templateName: 'review_photos_step',
defaultContext: function() {
return {
platformName: '',
- fullName: '',
+ fullName: ''
};
},
postRender: function() {
// Load the photos from the previous steps
- $( '#face_image' )[0].src = this.model.get('faceImage');
- $( '#photo_id_image' )[0].src = this.model.get('identificationImage');
+ $('#face_image')[0].src = this.model.get('faceImage');
+ $('#photo_id_image')[0].src = this.model.get('identificationImage');
// Prep the name change dropdown
- $( '.expandable-area' ).slideUp();
- $( '.is-expandable' ).addClass('is-ready');
- $( '.is-expandable .title-expand' ).on( 'click', this.expandCallback );
+ $('.expandable-area').slideUp();
+ $('.is-expandable').addClass('is-ready');
+ $('.is-expandable .title-expand').on('click', this.expandCallback);
// Go back to the first photo step if we need to retake photos
- $( '#retake_photos_button' ).on( 'click', _.bind( this.retakePhotos, this ) );
+ $('#retake_photos_button').on('click', _.bind(this.retakePhotos, this));
// When moving to the next step, submit photos for verification
- $( '#next_step_button' ).on( 'click', _.bind( this.submitPhotos, this ) );
+ $('#next_step_button').on('click', _.bind(this.submitPhotos, this));
// Track a virtual pageview, for easy funnel reconstruction.
- window.analytics.page( 'verification', this.templateName );
+ window.analytics.page('verification', this.templateName);
},
retakePhotos: function() {
// Track the user's intent to retake their photos
- window.analytics.track( 'edx.bi.user.images.retaken', {
+ window.analytics.track('edx.bi.user.images.retaken', {
category: 'verification'
});
- this.goToStep( 'face-photo-step' );
+ this.goToStep('face-photo-step');
},
submitPhotos: function() {
- var fullName = $( '#new-name' ).val();
+ var fullName = $('#new-name').val();
// Disable the submit button to prevent duplicate submissions
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
// On success, move on to the next step
- this.listenToOnce( this.model, 'sync', _.bind( this.nextStep, this ) );
+ this.listenToOnce(this.model, 'sync', _.bind(this.nextStep, this));
// On failure, re-enable the submit button and display the error
- this.listenToOnce( this.model, 'error', _.bind( this.handleSubmissionError, this ) );
+ this.listenToOnce(this.model, 'error', _.bind(this.handleSubmissionError, this));
// Submit
- if ( fullName ) {
- this.model.set( 'fullName', fullName );
+ if (fullName) {
+ this.model.set('fullName', fullName);
}
this.model.save();
},
- handleSubmissionError: function( xhr ) {
- var errorMsg = gettext( 'An error has occurred. Please try again later.' );
+ handleSubmissionError: function(xhr) {
+ var errorMsg = gettext('An error has occurred. Please try again later.');
// Re-enable the submit button to allow the user to retry
- this.setSubmitButtonEnabled( true );
+ this.setSubmitButtonEnabled(true);
- if ( xhr.status === 400 ) {
+ if (xhr.status === 400) {
errorMsg = xhr.responseText;
}
this.errorModel.set({
- errorTitle: gettext( 'Could not submit photos' ),
+ errorTitle: gettext('Could not submit photos'),
errorMsg: errorMsg,
shown: true
});
},
- expandCallback: function( event ) {
+ expandCallback: function(event) {
var $link = $(this),
$title = $link.closest('.help-tip'),
expanded = $title.hasClass('is-expanded');
event.preventDefault();
- $link.attr( 'aria-expanded', !expanded );
+ $link.attr('aria-expanded', !expanded);
$title.toggleClass('is-expanded')
.find('.expandable-area').slideToggle();
},
- setSubmitButtonEnabled: function( isEnabled ) {
- $( '#next_step_button' )
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ setSubmitButtonEnabled: function(isEnabled) {
+ $('#next_step_button')
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
}
});
-
-})( jQuery, gettext );
+})(jQuery, gettext);
diff --git a/lms/static/js/verify_student/views/step_view.js b/lms/static/js/verify_student/views/step_view.js
index fd5e941cb5..42ede52631 100644
--- a/lms/static/js/verify_student/views/step_view.js
+++ b/lms/static/js/verify_student/views/step_view.js
@@ -1,4 +1,4 @@
-/*global jQuery, _, Backbone, gettext */
+/* global jQuery, _, Backbone, gettext */
/**
* Base view for defining steps in the payment/verification flow.
@@ -10,55 +10,55 @@
*/
var edx = edx || {};
- (function( $, _, Backbone, gettext ) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.StepView = Backbone.View.extend({
+ edx.verify_student.StepView = Backbone.View.extend({
- initialize: function( obj ) {
- _.extend( this, obj );
+ initialize: function(obj) {
+ _.extend(this, obj);
/* Mix non-conflicting functions from underscore.string
* (all but include, contains, and reverse) into the
* Underscore namespace.
*/
- _.mixin(_.str.exports());
- },
+ _.mixin(_.str.exports());
+ },
- render: function() {
- var templateHtml = $( "#" + this.templateName + "-tpl" ).html();
+ render: function() {
+ var templateHtml = $('#' + this.templateName + '-tpl').html();
// Allow subclasses to add additional information
// to the template context, perhaps asynchronously.
- this.updateContext( this.templateContext() ).done(
- function( templateContext ) {
+ this.updateContext(this.templateContext()).done(
+ function(templateContext) {
// Render the template into the DOM
- edx.HtmlUtils.setHtml( $(this.el), edx.HtmlUtils.template(templateHtml)( templateContext ) );
+ edx.HtmlUtils.setHtml($(this.el), edx.HtmlUtils.template(templateHtml)(templateContext));
// Allow subclasses to install custom event handlers
this.postRender();
}
- ).fail( _.bind( this.handleError, this ) );
+ ).fail(_.bind(this.handleError, this));
- return this;
- },
+ return this;
+ },
- handleError: function( errorTitle, errorMsg ) {
- this.errorModel.set({
- errorTitle: errorTitle || gettext( "Error" ),
- errorMsg: errorMsg || gettext( "An error has occurred. Please try reloading the page." ),
- shown: true
- });
- },
+ handleError: function(errorTitle, errorMsg) {
+ this.errorModel.set({
+ errorTitle: errorTitle || gettext('Error'),
+ errorMsg: errorMsg || gettext('An error has occurred. Please try reloading the page.'),
+ shown: true
+ });
+ },
- templateContext: function() {
- var context = {
- nextStepTitle: this.nextStepTitle
- };
- return _.extend( context, this.defaultContext(), this.stepData );
- },
+ templateContext: function() {
+ var context = {
+ nextStepTitle: this.nextStepTitle
+ };
+ return _.extend(context, this.defaultContext(), this.stepData);
+ },
/**
* Provide default values for the template context.
@@ -68,9 +68,9 @@
* tests can pass in only the values relevant
* to the test.
*/
- defaultContext: function() {
- return {};
- },
+ defaultContext: function() {
+ return {};
+ },
/**
* Subclasses can override this to add information to
@@ -79,28 +79,27 @@
* after completing an AJAX request.
* The default implementation is a no-op.
*/
- updateContext: function( templateContext ) {
- var view = this;
- return $.Deferred(
- function( defer ) {
- defer.resolveWith( view, [ templateContext ]);
+ updateContext: function(templateContext) {
+ var view = this;
+ return $.Deferred(
+ function(defer) {
+ defer.resolveWith(view, [templateContext]);
}
).promise();
- },
+ },
- postRender: function() {
+ postRender: function() {
// Sub-classes can override this method
// to install custom event handlers.
- },
+ },
- nextStep: function() {
- this.trigger('next-step');
- },
+ nextStep: function() {
+ this.trigger('next-step');
+ },
- goToStep: function( stepName ) {
- this.trigger( 'go-to-step', stepName );
- }
+ goToStep: function(stepName) {
+ this.trigger('go-to-step', stepName);
+ }
- });
-
- })( jQuery, _, Backbone, gettext );
+ });
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/verify_student/views/webcam_photo_view.js b/lms/static/js/verify_student/views/webcam_photo_view.js
index 707bc0f797..b132f1b255 100644
--- a/lms/static/js/verify_student/views/webcam_photo_view.js
+++ b/lms/static/js/verify_student/views/webcam_photo_view.js
@@ -3,156 +3,156 @@
* Supports HTML5 and Flash.
*/
var edx = edx || {},
- key = {
- enter: 13
- };
+ key = {
+ enter: 13
+ };
- (function( $, _, Backbone, gettext ) {
- 'use strict';
+ (function($, _, Backbone, gettext) {
+ 'use strict';
- edx.verify_student = edx.verify_student || {};
+ edx.verify_student = edx.verify_student || {};
- edx.verify_student.WebcamPhotoView = Backbone.View.extend({
+ edx.verify_student.WebcamPhotoView = Backbone.View.extend({
- template: "#webcam_photo-tpl",
- el: "#webcam",
+ template: '#webcam_photo-tpl',
+ el: '#webcam',
- backends: {
- "html5": {
- name: "html5",
+ backends: {
+ 'html5': {
+ name: 'html5',
- initialize: function( obj ) {
- this.URL = (window.URL || window.webkitURL);
- this.video = obj.video || "";
- this.canvas = obj.canvas || "";
- this.stream = null;
+ initialize: function(obj) {
+ this.URL = (window.URL || window.webkitURL);
+ this.video = obj.video || '';
+ this.canvas = obj.canvas || '';
+ this.stream = null;
// Start the capture
- var getUserMedia = this.getUserMediaFunc();
- if ( getUserMedia ) {
- getUserMedia(
- {
- video: true,
+ var getUserMedia = this.getUserMediaFunc();
+ if (getUserMedia) {
+ getUserMedia(
+ {
+ video: true,
// Specify the `fake` constraint if we detect we are running in a test
// environment. In Chrome, this will do nothing, but in Firefox, it will
// instruct the browser to use a fake video device.
- fake: window.location.hostname === 'localhost'
- },
- _.bind( this.getUserMediaCallback, this ),
- _.bind( this.handleVideoFailure, this )
+ fake: window.location.hostname === 'localhost'
+ },
+ _.bind(this.getUserMediaCallback, this),
+ _.bind(this.handleVideoFailure, this)
);
- }
- },
+ }
+ },
- isSupported: function() {
- return this.getUserMediaFunc() !== undefined;
- },
+ isSupported: function() {
+ return this.getUserMediaFunc() !== undefined;
+ },
- snapshot: function() {
- var video;
+ snapshot: function() {
+ var video;
- if ( this.stream ) {
- video = this.getVideo();
- this.getCanvas().getContext('2d').drawImage( video, 0, 0 );
- video.pause();
- return true;
- }
+ if (this.stream) {
+ video = this.getVideo();
+ this.getCanvas().getContext('2d').drawImage(video, 0, 0);
+ video.pause();
+ return true;
+ }
- return false;
- },
+ return false;
+ },
- getImageData: function() {
- return this.getCanvas().toDataURL( 'image/png' );
- },
+ getImageData: function() {
+ return this.getCanvas().toDataURL('image/png');
+ },
- reset: function() {
- this.getVideo().play();
- },
+ reset: function() {
+ this.getVideo().play();
+ },
- getUserMediaFunc: function() {
- var userMedia = (
+ getUserMediaFunc: function() {
+ var userMedia = (
navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia
);
- if ( userMedia ) {
- return _.bind( userMedia, navigator );
- }
- },
+ if (userMedia) {
+ return _.bind(userMedia, navigator);
+ }
+ },
- getUserMediaCallback: function( stream ) {
- var video = this.getVideo();
- this.stream = stream;
- video.src = this.URL.createObjectURL( stream );
- video.play();
- this.trigger('webcam-loaded');
- },
+ getUserMediaCallback: function(stream) {
+ var video = this.getVideo();
+ this.stream = stream;
+ video.src = this.URL.createObjectURL(stream);
+ video.play();
+ this.trigger('webcam-loaded');
+ },
- getVideo: function() {
- return $( this.video ).first()[0];
- },
+ getVideo: function() {
+ return $(this.video).first()[0];
+ },
- getCanvas: function() {
- return $( this.canvas ).first()[0];
- },
+ getCanvas: function() {
+ return $(this.canvas).first()[0];
+ },
- handleVideoFailure: function() {
- this.trigger(
+ handleVideoFailure: function() {
+ this.trigger(
'error',
- gettext( 'Video Capture Error' ),
- gettext( 'Please verify that your webcam is connected and that you have allowed your browser to access it.' )
+ gettext('Video Capture Error'),
+ gettext('Please verify that your webcam is connected and that you have allowed your browser to access it.')
);
- }
- },
+ }
+ },
- "flash": {
+ 'flash': {
- name: "flash",
+ name: 'flash',
- initialize: function( obj ) {
- this.wrapper = obj.wrapper || "";
- this.imageData = "";
+ initialize: function(obj) {
+ this.wrapper = obj.wrapper || '';
+ this.imageData = '';
// Wait for the player to load, then verify camera support
// Trigger an error if no camera is available.
- this.checkCameraSupported();
- },
+ this.checkCameraSupported();
+ },
- isSupported: function() {
- try {
- var flashObj = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
- if ( flashObj ) {
- return true;
- }
- } catch(ex) {
- if ( navigator.mimeTypes["application/x-shockwave-flash"] !== undefined ) {
- return true;
- }
- }
+ isSupported: function() {
+ try {
+ var flashObj = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
+ if (flashObj) {
+ return true;
+ }
+ } catch (ex) {
+ if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) {
+ return true;
+ }
+ }
- return false;
- },
+ return false;
+ },
- snapshot: function() {
- var flashObj = this.getFlashObject();
- if ( flashObj.cameraAuthorized() ) {
- this.imageData = flashObj.snap();
- return true;
- }
- return false;
- },
+ snapshot: function() {
+ var flashObj = this.getFlashObject();
+ if (flashObj.cameraAuthorized()) {
+ this.imageData = flashObj.snap();
+ return true;
+ }
+ return false;
+ },
- reset: function() {
- this.getFlashObject().reset();
- },
+ reset: function() {
+ this.getFlashObject().reset();
+ },
- getImageData: function() {
- return this.imageData;
- },
+ getImageData: function() {
+ return this.imageData;
+ },
- flashObjectTag: function() {
- return (
+ flashObjectTag: function() {
+ return (
''
);
- },
+ },
- getFlashObject: function() {
- return $( "#flash_video" )[0];
- },
+ getFlashObject: function() {
+ return $('#flash_video')[0];
+ },
- checkCameraSupported: function() {
- var flashObj = this.getFlashObject(),
- isLoaded = false,
- hasCamera = false;
+ checkCameraSupported: function() {
+ var flashObj = this.getFlashObject(),
+ isLoaded = false,
+ hasCamera = false;
- isLoaded = (
+ isLoaded = (
flashObj &&
- flashObj.hasOwnProperty( 'percentLoaded' ) &&
+ flashObj.hasOwnProperty('percentLoaded') &&
flashObj.percentLoaded() === 100
);
// On some browsers, the flash object will say it has a camera
// even "percentLoaded" isn't defined.
- hasCamera = (
+ hasCamera = (
flashObj &&
- flashObj.hasOwnProperty( 'hasCamera' ) &&
+ flashObj.hasOwnProperty('hasCamera') &&
flashObj.hasCamera()
);
// If we've fully loaded, and no camera is available,
// then show an error.
- if ( isLoaded && !hasCamera ) {
- this.trigger(
+ if (isLoaded && !hasCamera) {
+ this.trigger(
'error',
- gettext( "No Webcam Detected" ),
- gettext( "You don't seem to have a webcam connected." ) + " " +
- gettext( "Double-check that your webcam is connected and working to continue.")
+ gettext('No Webcam Detected'),
+ gettext("You don't seem to have a webcam connected.") + ' ' +
+ gettext('Double-check that your webcam is connected and working to continue.')
);
- }
+ }
// If we're still waiting for the player to load, check
// back later.
- else if ( !isLoaded && !hasCamera ) {
- setTimeout( _.bind( this.checkCameraSupported, this ), 50 );
- }
+ else if (!isLoaded && !hasCamera) {
+ setTimeout(_.bind(this.checkCameraSupported, this), 50);
+ }
// Otherwise, the flash player says it has a camera,
// so we don't need to keep checking.
- }
- }
- },
+ }
+ }
+ },
- initialize: function( obj ) {
- this.submitButton = obj.submitButton || "";
- this.modelAttribute = obj.modelAttribute || "";
- this.errorModel = obj.errorModel || null;
- this.backend = this.backends[obj.backendName] || obj.backend;
- this.captureSoundPath = obj.captureSoundPath || "";
+ initialize: function(obj) {
+ this.submitButton = obj.submitButton || '';
+ this.modelAttribute = obj.modelAttribute || '';
+ this.errorModel = obj.errorModel || null;
+ this.backend = this.backends[obj.backendName] || obj.backend;
+ this.captureSoundPath = obj.captureSoundPath || '';
- _.extend( this.backend, Backbone.Events );
- this.backend.initialize({
- wrapper: "#camera",
- video: '#photo_id_video',
- canvas: '#photo_id_canvas'
- });
+ _.extend(this.backend, Backbone.Events);
+ this.backend.initialize({
+ wrapper: '#camera',
+ video: '#photo_id_video',
+ canvas: '#photo_id_canvas'
+ });
- this.listenTo( this.backend, 'error', this.handleError );
- this.listenTo( this.backend, 'webcam-loaded', this.handleWebcamLoaded );
- },
+ this.listenTo(this.backend, 'error', this.handleError);
+ this.listenTo(this.backend, 'webcam-loaded', this.handleWebcamLoaded);
+ },
- isSupported: function() {
- return this.backend.isSupported();
- },
+ isSupported: function() {
+ return this.backend.isSupported();
+ },
- render: function() {
- var renderedHtml,
- $resetBtn,
- $captureBtn;
+ render: function() {
+ var renderedHtml,
+ $resetBtn,
+ $captureBtn;
// Set the submit button to disabled by default
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
// Load the template for the webcam into the DOM
- renderedHtml = _.template($( this.template ).html())(
- { backendName: this.backend.name }
+ renderedHtml = _.template($(this.template).html())(
+ {backendName: this.backend.name}
);
- $( this.el ).html( renderedHtml );
+ $(this.el).html(renderedHtml);
- $resetBtn = this.$el.find('#webcam_reset_button');
- $captureBtn = this.$el.find('#webcam_capture_button');
+ $resetBtn = this.$el.find('#webcam_reset_button');
+ $captureBtn = this.$el.find('#webcam_capture_button');
// Install event handlers
- $resetBtn.on( 'click', _.bind( this.reset, this ) );
- $captureBtn.on( 'click', _.bind( this.capture, this ) );
+ $resetBtn.on('click', _.bind(this.reset, this));
+ $captureBtn.on('click', _.bind(this.capture, this));
- $resetBtn.on( 'keyup', _.bind( this.resetByEnter, this ) );
+ $resetBtn.on('keyup', _.bind(this.resetByEnter, this));
// Show the capture button
- $captureBtn.removeClass('is-hidden');
- $( "#webcam_capture_button", this.el ).removeClass('is-hidden');
- $( "#webcam_capture_sound", this.el ).attr('src', this.captureSoundPath);
+ $captureBtn.removeClass('is-hidden');
+ $('#webcam_capture_button', this.el).removeClass('is-hidden');
+ $('#webcam_capture_sound', this.el).attr('src', this.captureSoundPath);
- return this;
- },
+ return this;
+ },
- reset: function() {
+ reset: function() {
// Disable the submit button
- this.setSubmitButtonEnabled( false );
+ this.setSubmitButtonEnabled(false);
// Reset the video capture
- this.backend.reset();
+ this.backend.reset();
// Reset data on the model
- this.model.set( this.modelAttribute, "" );
+ this.model.set(this.modelAttribute, '');
// Go back to the initial button state
- $( "#webcam_reset_button", this.el ).addClass('is-hidden');
- $( "#webcam_capture_button", this.el ).removeClass('is-hidden');
- $( this.submitButton ).attr('title', '');
- },
+ $('#webcam_reset_button', this.el).addClass('is-hidden');
+ $('#webcam_capture_button', this.el).removeClass('is-hidden');
+ $(this.submitButton).attr('title', '');
+ },
- resetByEnter: function(event){
- if(event.keyCode == key.enter){
- this.reset();
- }
- },
- capture: function() {
+ resetByEnter: function(event) {
+ if (event.keyCode == key.enter) {
+ this.reset();
+ }
+ },
+ capture: function() {
// Take a snapshot of the video
- var success = this.backend.snapshot();
+ var success = this.backend.snapshot();
- if ( success ) {
+ if (success) {
// Trigger an event which parent views can use to fire a
// business intelligence event
- this.trigger( 'imageCaptured' );
+ this.trigger('imageCaptured');
// Hide the capture button, and show the reset button
- $( "#webcam_capture_button", this.el ).addClass('is-hidden');
- $( "#webcam_reset_button", this.el ).removeClass('is-hidden');
+ $('#webcam_capture_button', this.el).addClass('is-hidden');
+ $('#webcam_reset_button', this.el).removeClass('is-hidden');
// Save the data to the model
- this.model.set( this.modelAttribute, this.backend.getImageData() );
+ this.model.set(this.modelAttribute, this.backend.getImageData());
// Enable the submit button
- this.setSubmitButtonEnabled( true );
- this.setSubmitButtonFocused();
- this.captureSound();
- }
- },
+ this.setSubmitButtonEnabled(true);
+ this.setSubmitButtonFocused();
+ this.captureSound();
+ }
+ },
- handleWebcamLoaded: function( errorTitle, errorMsg ) {
+ handleWebcamLoaded: function(errorTitle, errorMsg) {
// Hide the text behind camera
- $( "#camera .placeholder-art", this.el ).hide();
- },
+ $('#camera .placeholder-art', this.el).hide();
+ },
- handleError: function( errorTitle, errorMsg ) {
+ handleError: function(errorTitle, errorMsg) {
// Hide the buttons
- $( "#webcam_capture_button", this.el ).addClass('is-hidden');
- $( "#webcam_reset_button", this.el ).addClass('is-hidden');
+ $('#webcam_capture_button', this.el).addClass('is-hidden');
+ $('#webcam_reset_button', this.el).addClass('is-hidden');
// Show the error message
- if ( this.errorModel ) {
- this.errorModel.set({
- errorTitle: errorTitle,
- errorMsg: errorMsg,
- shown: true
- });
- }
- },
+ if (this.errorModel) {
+ this.errorModel.set({
+ errorTitle: errorTitle,
+ errorMsg: errorMsg,
+ shown: true
+ });
+ }
+ },
- setSubmitButtonEnabled: function( isEnabled ) {
- $( this.submitButton )
- .toggleClass( 'is-disabled', !isEnabled )
- .prop( 'disabled', !isEnabled )
+ setSubmitButtonEnabled: function(isEnabled) {
+ $(this.submitButton)
+ .toggleClass('is-disabled', !isEnabled)
+ .prop('disabled', !isEnabled)
.attr('aria-disabled', !isEnabled);
- },
+ },
- captureSound: function(){
- $( '#webcam_capture_sound' )[0].play();
- },
+ captureSound: function() {
+ $('#webcam_capture_sound')[0].play();
+ },
- setSubmitButtonFocused: function(){
- $( this.submitButton )
+ setSubmitButtonFocused: function() {
+ $(this.submitButton)
.trigger('focus')
- .attr('title', gettext( 'Photo Captured successfully.'));
- },
+ .attr('title', gettext('Photo Captured successfully.'));
+ },
- isMobileDevice: function() {
+ isMobileDevice: function() {
// Check whether user is using mobile device or not
- return ( navigator.userAgent.match(/(Android|iPad|iPhone|iPod)/g) ? true : false );
- }
- });
+ return (navigator.userAgent.match(/(Android|iPad|iPhone|iPod)/g) ? true : false);
+ }
+ });
/**
* Retrieve a supported webcam view implementation.
@@ -363,37 +363,36 @@
* @param {Object} obj Parameters to the webcam view.
* @return {Object} A Backbone view.
*/
- edx.verify_student.getSupportedWebcamView = function( obj ) {
- var view = null;
+ edx.verify_student.getSupportedWebcamView = function(obj) {
+ var view = null;
// First choice is HTML5, supported by most web browsers
- obj.backendName = "html5";
- view = new edx.verify_student.WebcamPhotoView( obj );
- if ( view.isSupported() ) {
- return view;
- }
+ obj.backendName = 'html5';
+ view = new edx.verify_student.WebcamPhotoView(obj);
+ if (view.isSupported()) {
+ return view;
+ }
// Second choice is Flash, required for older versions of IE
- obj.backendName = "flash";
- view = new edx.verify_student.WebcamPhotoView( obj );
- if ( view.isSupported() ) {
- return view;
- }
+ obj.backendName = 'flash';
+ view = new edx.verify_student.WebcamPhotoView(obj);
+ if (view.isSupported()) {
+ return view;
+ }
// If user is not using mobile device and Flash is not available
// then show user error message for Flash
- if (!view.isMobileDevice() && !view.isSupported()) {
- view.backend.trigger(
+ if (!view.isMobileDevice() && !view.isSupported()) {
+ view.backend.trigger(
'error',
- gettext( "No Flash Detected" ),
- gettext( "You don't seem to have Flash installed. Get Flash to continue your verification." )
+ gettext('No Flash Detected'),
+ gettext("You don't seem to have Flash installed. Get Flash to continue your verification.")
);
- return view;
- }
+ return view;
+ }
// Last resort is HTML file input with image capture.
// This will work everywhere, and on iOS it will
// allow users to take a photo with the camera.
- return new edx.verify_student.ImageInputView( obj );
- };
-
- })( jQuery, _, Backbone, gettext );
+ return new edx.verify_student.ImageInputView(obj);
+ };
+ })(jQuery, _, Backbone, gettext);
diff --git a/lms/static/js/views/fields.js b/lms/static/js/views/fields.js
index 762f342234..ccf44340f1 100644
--- a/lms/static/js/views/fields.js
+++ b/lms/static/js/views/fields.js
@@ -1,4 +1,4 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone',
@@ -9,14 +9,13 @@
'text!templates/fields/field_text.underscore',
'text!templates/fields/field_textarea.underscore',
'backbone-super'
- ], function (gettext, $, _, Backbone, HtmlUtils,
+ ], function(gettext, $, _, Backbone, HtmlUtils,
field_readonly_template,
field_dropdown_template,
field_link_template,
field_text_template,
field_textarea_template
) {
-
var messageRevertDelay = 6000;
var FieldViews = {};
@@ -24,7 +23,7 @@
fieldType: 'generic',
- className: function () {
+ className: function() {
return 'u-field' + ' u-field-' + this.fieldType + ' u-field-' + this.options.valueAttribute;
},
@@ -33,34 +32,34 @@
indicators: {
'canEdit': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Editable"),
+ gettext('Editable'),
HtmlUtils.HTML('')
),
'error': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Error"),
+ gettext('Error'),
HtmlUtils.HTML('')
),
'validationError': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Validation Error"),
+ gettext('Validation Error'),
HtmlUtils.HTML('')
),
'inProgress': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("In Progress"),
+ gettext('In Progress'),
HtmlUtils.HTML('')
),
'success': HtmlUtils.joinHtml(
HtmlUtils.HTML(''), // eslint-disable-line max-len
- gettext("Success"),
+ gettext('Success'),
HtmlUtils.HTML('')
),
'plus': HtmlUtils.joinHtml(
HtmlUtils.HTML(''),
- gettext("Placeholder"),
+ gettext('Placeholder'),
HtmlUtils.HTML('')
- ),
+ )
},
messages: {
@@ -76,20 +75,19 @@
Backbone.View.apply(this, arguments);
},
- initialize: function () {
-
+ initialize: function() {
this.template = _.template(this.fieldTemplate || '');
this.helpMessage = this.options.helpMessage || '';
this.showMessages = _.isUndefined(this.options.showMessages) ? true : this.options.showMessages;
- _.bindAll(this, 'modelValue', 'modelValueIsSet', 'showNotificationMessage','getNotificationMessage',
+ _.bindAll(this, 'modelValue', 'modelValueIsSet', 'showNotificationMessage', 'getNotificationMessage',
'getMessage', 'title', 'showHelpMessage', 'showInProgressMessage', 'showSuccessMessage',
'showErrorMessage'
);
},
- modelValue: function () {
+ modelValue: function() {
return this.model.get(this.options.valueAttribute);
},
@@ -97,7 +95,7 @@
return (this.modelValue() === true);
},
- title: function (title) {
+ title: function(title) {
return HtmlUtils.setHtml(this.$('.u-field-title'), title);
},
@@ -110,7 +108,7 @@
return this.indicators[message_status];
},
- showHelpMessage: function (message) {
+ showHelpMessage: function(message) {
if (_.isUndefined(message) || _.isNull(message)) {
message = this.helpMessage;
}
@@ -135,11 +133,11 @@
}
},
- showInProgressMessage: function () {
+ showInProgressMessage: function() {
this.showNotificationMessage(this.getMessage('inProgress'));
},
- showSuccessMessage: function () {
+ showSuccessMessage: function() {
var successMessage = this.getMessage('success');
this.showNotificationMessage(successMessage);
@@ -152,7 +150,7 @@
var context = Date.now();
this.lastSuccessMessageContext = context;
- setTimeout(function () {
+ setTimeout(function() {
if ((context === view.lastSuccessMessageContext) &&
(view.getNotificationMessage().toString() === successMessage.toString())) {
if (view.editable === 'toggle') {
@@ -164,7 +162,7 @@
}, messageRevertDelay);
},
- showErrorMessage: function (xhr) {
+ showErrorMessage: function(xhr) {
if (xhr.status === 400) {
try {
var errors = JSON.parse(xhr.responseText),
@@ -182,14 +180,14 @@
FieldViews.EditableFieldView = FieldViews.FieldView.extend({
- initialize: function (options) {
+ initialize: function(options) {
this.persistChanges = _.isUndefined(options.persistChanges) ? false : options.persistChanges;
_.bindAll(this, 'saveAttributes', 'saveSucceeded', 'showDisplayMode', 'showEditMode',
'startEditing', 'finishEditing'
);
this._super(options);
- this.editable = _.isUndefined(this.options.editable) ? 'always': this.options.editable;
+ this.editable = _.isUndefined(this.options.editable) ? 'always' : this.options.editable;
this.$el.addClass('editable-' + this.editable);
if (this.editable === 'always') {
@@ -199,17 +197,17 @@
}
},
- saveAttributes: function (attributes, options) {
+ saveAttributes: function(attributes, options) {
if (this.persistChanges === true) {
var view = this;
var defaultOptions = {
contentType: 'application/merge-patch+json',
patch: true,
wait: true,
- success: function () {
+ success: function() {
view.saveSucceeded();
},
- error: function (model, xhr) {
+ error: function(model, xhr) {
view.showErrorMessage(xhr);
}
};
@@ -218,7 +216,7 @@
}
},
- saveSucceeded: function () {
+ saveSucceeded: function() {
this.showSuccessMessage();
},
@@ -247,7 +245,7 @@
this.$el.addClass('mode-edit');
},
- startEditing: function () {
+ startEditing: function() {
if (this.editable === 'toggle' && this.mode !== 'edit') {
this.showEditMode(true);
}
@@ -255,7 +253,7 @@
finishEditing: function() {
var modelValue;
- if (this.persistChanges === false || this.mode !== 'edit') {return;}
+ if (this.persistChanges === false || this.mode !== 'edit') { return; }
modelValue = this.modelValue();
if (!(_.isUndefined(modelValue) || _.isNull(modelValue))) {
@@ -273,11 +271,11 @@
}
},
- highlightFieldOnError: function () {
+ highlightFieldOnError: function() {
this.$el.addClass('error');
},
- unhighlightField: function () {
+ unhighlightField: function() {
this.$el.removeClass('error');
}
});
@@ -288,13 +286,13 @@
fieldTemplate: field_readonly_template,
- initialize: function (options) {
+ initialize: function(options) {
this._super(options);
_.bindAll(this, 'render', 'fieldValue', 'updateValueInField');
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateValueInField);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
title: this.options.title,
@@ -306,11 +304,11 @@
return this;
},
- fieldValue: function () {
+ fieldValue: function() {
return this.$('.u-field-value').text();
},
- updateValueInField: function () {
+ updateValueInField: function() {
this.$('.u-field-value ').text(this.modelValue());
}
});
@@ -325,13 +323,13 @@
'change input': 'saveValue'
},
- initialize: function (options) {
+ initialize: function(options) {
this._super(options);
_.bindAll(this, 'render', 'fieldValue', 'updateValueInField', 'saveValue');
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateValueInField);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
title: this.options.title,
@@ -342,16 +340,16 @@
return this;
},
- fieldValue: function () {
+ fieldValue: function() {
return this.$('.u-field-value input').val();
},
- updateValueInField: function () {
+ updateValueInField: function() {
var value = (_.isUndefined(this.modelValue()) || _.isNull(this.modelValue())) ? '' : this.modelValue();
this.$('.u-field-value input').val(value);
},
- saveValue: function () {
+ saveValue: function() {
var attributes = {};
attributes[this.options.valueAttribute] = this.fieldValue();
this.saveAttributes(attributes);
@@ -370,14 +368,14 @@
'focusout select': 'finishEditing'
},
- initialize: function (options) {
+ initialize: function(options) {
_.bindAll(this, 'render', 'optionForValue', 'fieldValue', 'displayValue', 'updateValueInField', 'saveValue');
this._super(options);
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateValueInField);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField);
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
mode: this.mode,
@@ -412,10 +410,10 @@
return _.find(this.options.options, function(option) { return option[0] === value; });
},
- fieldValue: function () {
+ fieldValue: function() {
var value;
if (this.editable === 'never') {
- value = this.modelValueIsSet() ? this.modelValue () : null;
+ value = this.modelValueIsSet() ? this.modelValue() : null;
}
else {
value = this.$('.u-field-value select').val();
@@ -423,7 +421,7 @@
return value === '' ? null : value;
},
- displayValue: function (value) {
+ displayValue: function(value) {
if (value) {
var option = this.optionForValue(value);
return (option ? option[1] : '');
@@ -432,7 +430,7 @@
}
},
- updateValueInField: function () {
+ updateValueInField: function() {
if (this.editable !== 'never') {
this.$('.u-field-value select').val(this.modelValue() || '');
}
@@ -449,7 +447,7 @@
}
},
- saveValue: function () {
+ saveValue: function() {
var attributes = {};
attributes[this.options.valueAttribute] = this.fieldValue();
this.saveAttributes(attributes);
@@ -505,13 +503,13 @@
'cut textarea': 'adjustTextareaHeight'
},
- initialize: function (options) {
+ initialize: function(options) {
_.bindAll(this, 'render', 'onKeyDown', 'adjustTextareaHeight', 'fieldValue', 'saveValue', 'updateView');
this._super(options);
- this.listenTo(this.model, "change:" + this.options.valueAttribute, this.updateView);
+ this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateView);
},
- render: function () {
+ render: function() {
var value = this.modelValue();
if (this.mode === 'display') {
value = value || this.options.placeholderValue;
@@ -536,7 +534,7 @@
return this;
},
- onKeyDown: function (event) {
+ onKeyDown: function(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.finishEditing(event);
@@ -546,7 +544,7 @@
},
adjustTextareaHeight: function() {
- if (this.persistChanges === false) {return;}
+ if (this.persistChanges === false) { return; }
var textarea = this.$('textarea');
textarea.css('height', 'auto').css('height', textarea.prop('scrollHeight') + 10);
},
@@ -556,7 +554,7 @@
return value ? $.trim(value) : '';
},
- fieldValue: function () {
+ fieldValue: function() {
if (this.mode === 'edit') {
return this.$('.u-field-value textarea').val();
}
@@ -565,13 +563,13 @@
}
},
- saveValue: function () {
+ saveValue: function() {
var attributes = {};
attributes[this.options.valueAttribute] = this.fieldValue();
this.saveAttributes(attributes);
},
- updateView: function () {
+ updateView: function() {
if (this.mode !== 'edit') {
this.showDisplayMode(true);
}
@@ -606,12 +604,12 @@
'click a': 'linkClicked'
},
- initialize: function (options) {
+ initialize: function(options) {
this._super(options);
_.bindAll(this, 'render', 'linkClicked');
},
- render: function () {
+ render: function() {
HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.fieldTemplate)({
id: this.options.valueAttribute,
title: this.options.title,
@@ -624,7 +622,7 @@
return this;
},
- linkClicked: function (event) {
+ linkClicked: function(event) {
event.preventDefault();
}
});
diff --git a/lms/static/js/views/file_uploader.js b/lms/static/js/views/file_uploader.js
index 9dc064dd61..0f7c94280a 100644
--- a/lms/static/js/views/file_uploader.js
+++ b/lms/static/js/views/file_uploader.js
@@ -22,16 +22,16 @@
* @param errorNotification, optional callback that can return a success NotificationModel for display
* after a file failed to upload. This method will be passed the attempted file, event, and data.
*/
-(function (Backbone, $, _, gettext, interpolate_text, NotificationModel, NotificationView) {
+(function(Backbone, $, _, gettext, interpolate_text, NotificationModel, NotificationView) {
// Requires JQuery-File-Upload.
var FileUploaderView = Backbone.View.extend({
- initialize: function (options) {
+ initialize: function(options) {
this.template = _.template($('#file-upload-tpl').text());
this.options = options;
},
- render: function () {
+ render: function() {
var options = this.options,
get_option_with_default = function(option, default_value) {
var optionVal = options[option];
@@ -40,12 +40,12 @@
submitButton, resultNotification;
this.$el.html(this.template({
- title: get_option_with_default("title", ""),
- inputLabel: get_option_with_default("inputLabel", ""),
- inputTip: get_option_with_default("inputTip", ""),
- extensions: get_option_with_default("extensions", ""),
- submitButtonText: get_option_with_default("submitButtonText", gettext("Upload File")),
- url: get_option_with_default("url", "")
+ title: get_option_with_default('title', ''),
+ inputLabel: get_option_with_default('inputLabel', ''),
+ inputTip: get_option_with_default('inputTip', ''),
+ extensions: get_option_with_default('extensions', ''),
+ submitButtonText: get_option_with_default('submitButtonText', gettext('Upload File')),
+ url: get_option_with_default('url', '')
}));
submitButton = this.$el.find('.submit-file-button');
@@ -58,22 +58,22 @@
fail: this.errorHandler.bind(this),
autoUpload: false,
replaceFileInput: false,
- add: function (e, data) {
+ add: function(e, data) {
var file = data.files[0];
- submitButton.removeClass("is-disabled").attr('aria-disabled', false);
+ submitButton.removeClass('is-disabled').attr('aria-disabled', false);
submitButton.unbind('click');
- submitButton.click(function (event) {
+ submitButton.click(function(event) {
event.preventDefault();
data.submit();
});
- resultNotification.html("");
+ resultNotification.html('');
}
});
return this;
},
- successHandler: function (event, data) {
+ successHandler: function(event, data) {
var file = data.files[0].name;
var notificationModel;
if (this.options.successNotification) {
@@ -81,7 +81,7 @@
}
else {
notificationModel = new NotificationModel({
- type: "confirmation",
+ type: 'confirmation',
title: interpolate_text(gettext("Your upload of '{file}' succeeded."), {file: file})
});
}
@@ -92,7 +92,7 @@
notification.render();
},
- errorHandler: function (event, data) {
+ errorHandler: function(event, data) {
var file = data.files[0].name, message = null, jqXHR = data.response().jqXHR;
var notificationModel;
if (this.options.errorNotification) {
@@ -110,7 +110,7 @@
message = interpolate_text(gettext("Your upload of '{file}' failed."), {file: file});
}
notificationModel = new NotificationModel({
- type: "error",
+ type: 'error',
title: message
});
}
diff --git a/lms/static/js/views/image_field.js b/lms/static/js/views/image_field.js
index 43bb565d26..ae3bbdf3e4 100644
--- a/lms/static/js/views/image_field.js
+++ b/lms/static/js/views/image_field.js
@@ -1,11 +1,10 @@
-;(function (define) {
+(function(define) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'js/views/fields',
'text!templates/fields/field_image.underscore',
'backbone-super', 'jquery.fileupload'
- ], function (gettext, $, _, Backbone, FieldViews, field_image_template) {
-
+ ], function(gettext, $, _, Backbone, FieldViews, field_image_template) {
var ImageFieldView = FieldViews.FieldView.extend({
fieldType: 'image',
@@ -13,21 +12,21 @@
fieldTemplate: field_image_template,
uploadButtonSelector: '.upload-button-input',
- titleAdd: gettext("Upload an image"),
- titleEdit: gettext("Change image"),
- titleRemove: gettext("Remove"),
+ titleAdd: gettext('Upload an image'),
+ titleEdit: gettext('Change image'),
+ titleRemove: gettext('Remove'),
- titleUploading: gettext("Uploading"),
- titleRemoving: gettext("Removing"),
+ titleUploading: gettext('Uploading'),
+ titleRemoving: gettext('Removing'),
titleImageAlt: '',
- screenReaderTitle: gettext("Image"),
+ screenReaderTitle: gettext('Image'),
iconUpload: '',
iconRemove: '',
iconProgress: '',
- errorMessage: gettext("An error has occurred. Refresh the page, and then try again."),
+ errorMessage: gettext('An error has occurred. Refresh the page, and then try again.'),
events: {
'click .u-field-upload-button': 'clickedUploadButton',
@@ -37,14 +36,14 @@
'blur .upload-button-input': 'hideHoverState'
},
- initialize: function (options) {
+ initialize: function(options) {
this.options = _.extend({}, options);
this._super(options);
_.bindAll(this, 'render', 'imageChangeSucceeded', 'imageChangeFailed', 'fileSelected',
'watchForPageUnload', 'onBeforeUnload');
},
- render: function () {
+ render: function() {
this.$el.html(this.template({
id: this.options.valueAttribute,
inputName: (this.options.inputName || 'file'),
@@ -62,23 +61,23 @@
return this;
},
- showHoverState: function () {
+ showHoverState: function() {
this.$('.u-field-upload-button').addClass('button-visible');
},
- hideHoverState: function () {
+ hideHoverState: function() {
this.$('.u-field-upload-button').removeClass('button-visible');
},
- showErrorMessage: function (message) {
+ showErrorMessage: function(message) {
return message;
},
- imageUrl: function () {
+ imageUrl: function() {
return '';
},
- uploadButtonTitle: function () {
+ uploadButtonTitle: function() {
if (this.isShowingPlaceholder()) {
return _.result(this, 'titleAdd');
} else {
@@ -86,27 +85,27 @@
}
},
- removeButtonTitle: function () {
+ removeButtonTitle: function() {
return this.titleRemove;
},
- isEditingAllowed: function () {
+ isEditingAllowed: function() {
return true;
},
- isShowingPlaceholder: function () {
+ isShowingPlaceholder: function() {
return false;
},
- setUploadButtonVisibility: function (state) {
+ setUploadButtonVisibility: function(state) {
this.$('.u-field-upload-button').css('display', state);
},
- setRemoveButtonVisibility: function (state) {
+ setRemoveButtonVisibility: function(state) {
this.$('.u-field-remove-button').css('display', state);
},
- updateButtonsVisibility: function () {
+ updateButtonsVisibility: function() {
if (!this.isEditingAllowed() || !this.options.editable) {
this.setUploadButtonVisibility('none');
}
@@ -116,7 +115,7 @@
}
},
- clickedUploadButton: function () {
+ clickedUploadButton: function() {
$(this.uploadButtonSelector).fileupload({
url: this.options.imageUploadUrl,
type: 'POST',
@@ -126,7 +125,7 @@
});
},
- clickedRemoveButton: function () {
+ clickedRemoveButton: function() {
var view = this;
this.setCurrentStatus('removing');
this.setUploadButtonVisibility('none');
@@ -134,24 +133,24 @@
$.ajax({
type: 'POST',
url: this.options.imageRemoveUrl
- }).done(function () {
+ }).done(function() {
view.imageChangeSucceeded();
- }).fail(function (jqXHR) {
+ }).fail(function(jqXHR) {
view.showImageChangeFailedMessage(jqXHR.status, jqXHR.responseText);
});
},
- imageChangeSucceeded: function () {
+ imageChangeSucceeded: function() {
this.render();
},
- imageChangeFailed: function (e, data) {
+ imageChangeFailed: function(e, data) {
},
- showImageChangeFailedMessage: function (status, responseText) {
+ showImageChangeFailedMessage: function(status, responseText) {
},
- fileSelected: function (e, data) {
+ fileSelected: function(e, data) {
if (_.isUndefined(data.files[0].size) || this.validateImageSize(data.files[0].size)) {
this.setCurrentStatus('uploading');
this.setRemoveButtonVisibility('none');
@@ -160,13 +159,13 @@
}
},
- validateImageSize: function (imageBytes) {
+ validateImageSize: function(imageBytes) {
var humanReadableSize;
if (imageBytes < this.options.imageMinBytes) {
humanReadableSize = this.bytesToHumanReadable(this.options.imageMinBytes);
this.showErrorMessage(
interpolate_text(
- gettext("The file must be at least {size} in size."), {size: humanReadableSize}
+ gettext('The file must be at least {size} in size.'), {size: humanReadableSize}
)
);
return false;
@@ -174,7 +173,7 @@
humanReadableSize = this.bytesToHumanReadable(this.options.imageMaxBytes);
this.showErrorMessage(
interpolate_text(
- gettext("The file must be smaller than {size} in size."), {size: humanReadableSize}
+ gettext('The file must be smaller than {size} in size.'), {size: humanReadableSize}
)
);
return false;
@@ -182,47 +181,47 @@
return true;
},
- showUploadInProgressMessage: function () {
+ showUploadInProgressMessage: function() {
this.$('.u-field-upload-button').css('opacity', 1);
this.$('.upload-button-icon').html(this.iconProgress);
this.$('.upload-button-title').html(this.titleUploading);
},
- showRemovalInProgressMessage: function () {
+ showRemovalInProgressMessage: function() {
this.$('.u-field-remove-button').css('opacity', 1);
this.$('.remove-button-icon').html(this.iconProgress);
this.$('.remove-button-title').html(this.titleRemoving);
},
- setCurrentStatus: function (status) {
+ setCurrentStatus: function(status) {
this.$('.image-wrapper').attr('data-status', status);
},
- getCurrentStatus: function () {
+ getCurrentStatus: function() {
return this.$('.image-wrapper').attr('data-status');
},
- watchForPageUnload: function () {
+ watchForPageUnload: function() {
$(window).on('beforeunload', this.onBeforeUnload);
},
- onBeforeUnload: function () {
+ onBeforeUnload: function() {
var status = this.getCurrentStatus();
if (status === 'uploading') {
- return gettext("Upload is in progress. To avoid errors, stay on this page until the process is complete.");
+ return gettext('Upload is in progress. To avoid errors, stay on this page until the process is complete.');
} else if (status === 'removing') {
- return gettext("Removal is in progress. To avoid errors, stay on this page until the process is complete.");
+ return gettext('Removal is in progress. To avoid errors, stay on this page until the process is complete.');
}
},
- bytesToHumanReadable: function (size) {
+ bytesToHumanReadable: function(size) {
var units = [gettext('bytes'), gettext('KB'), gettext('MB')];
var i = 0;
- while(size >= 1024) {
+ while (size >= 1024) {
size /= 1024;
++i;
}
- return size.toFixed(1)*1 + ' ' + units[i];
+ return size.toFixed(1) * 1 + ' ' + units[i];
}
});
diff --git a/lms/static/js/views/message_banner.js b/lms/static/js/views/message_banner.js
index 8dc6157215..f256da61e8 100644
--- a/lms/static/js/views/message_banner.js
+++ b/lms/static/js/views/message_banner.js
@@ -1,19 +1,18 @@
-;(function (define, undefined) {
+(function(define, undefined) {
'use strict';
define([
'gettext', 'jquery', 'underscore', 'backbone', 'text!templates/fields/message_banner.underscore'
- ], function (gettext, $, _, Backbone, messageBannerTemplate) {
-
+ ], function(gettext, $, _, Backbone, messageBannerTemplate) {
var MessageBannerView = Backbone.View.extend({
- initialize: function (options) {
+ initialize: function(options) {
if (_.isUndefined(options)) {
options = {};
}
this.options = _.defaults(options, {urgency: 'high', type: ''});
},
- render: function () {
+ render: function() {
if (_.isUndefined(this.message) || _.isNull(this.message)) {
this.$el.html('');
} else {
@@ -24,12 +23,12 @@
return this;
},
- showMessage: function (message) {
+ showMessage: function(message) {
this.message = message;
this.render();
},
- hideMessage: function () {
+ hideMessage: function() {
this.message = null;
this.render();
}
diff --git a/lms/static/js/views/notification.js b/lms/static/js/views/notification.js
index f0d61b5f6b..a5cc328f17 100644
--- a/lms/static/js/views/notification.js
+++ b/lms/static/js/views/notification.js
@@ -1,7 +1,7 @@
(function(Backbone, $, _) {
var NotificationView = Backbone.View.extend({
- events : {
- "click .action-primary": "triggerCallback"
+ events: {
+ 'click .action-primary': 'triggerCallback'
},
initialize: function() {
@@ -10,13 +10,13 @@
render: function() {
this.$el.html(this.template({
- type: this.model.get("type"),
- title: this.model.get("title"),
- message: this.model.get("message"),
- details: this.model.get("details"),
- actionText: this.model.get("actionText"),
- actionClass: this.model.get("actionClass"),
- actionIconClass: this.model.get("actionIconClass")
+ type: this.model.get('type'),
+ title: this.model.get('title'),
+ message: this.model.get('message'),
+ details: this.model.get('details'),
+ actionText: this.model.get('actionText'),
+ actionClass: this.model.get('actionClass'),
+ actionIconClass: this.model.get('actionIconClass')
}));
this.$('.message').focus();
return this;
@@ -24,7 +24,7 @@
triggerCallback: function(event) {
event.preventDefault();
- var actionCallback = this.model.get("actionCallback");
+ var actionCallback = this.model.get('actionCallback');
if (actionCallback) {
actionCallback(this);
}
diff --git a/lms/static/js/wiki/CodeMirror.init.js b/lms/static/js/wiki/CodeMirror.init.js
index 76bfbfdd9f..c0f3515fb8 100644
--- a/lms/static/js/wiki/CodeMirror.init.js
+++ b/lms/static/js/wiki/CodeMirror.init.js
@@ -1,24 +1,22 @@
$(document).ready(function() {
+ var editor = CodeMirror.fromTextArea(document.getElementById('id_content'), {
+ mode: 'edx_markdown',
+ matchBrackets: true,
+ theme: 'default',
+ lineWrapping: true,
+ keyMap: 'accessible'
+ });
- var editor = CodeMirror.fromTextArea(document.getElementById("id_content"), {
- mode: 'edx_markdown',
- matchBrackets: true,
- theme: "default",
- lineWrapping: true,
- keyMap: "accessible"
- });
+ // Store the inital contents so we can compare for unsaved changes
+ var initial_contents = editor.getValue();
- //Store the inital contents so we can compare for unsaved changes
- var initial_contents = editor.getValue();
-
- window.onbeforeunload = function askConfirm() { //Warn the user before they navigate away
- if ( editor.getValue() != initial_contents ) {
- return "You have made changes to the article that have not been saved yet.";
- }
- };
-
- $(".btn-primary").click(function() {
- initial_contents = editor.getValue();
- });
+ window.onbeforeunload = function askConfirm() { // Warn the user before they navigate away
+ if (editor.getValue() != initial_contents) {
+ return 'You have made changes to the article that have not been saved yet.';
+ }
+ };
+ $('.btn-primary').click(function() {
+ initial_contents = editor.getValue();
+ });
});
diff --git a/lms/static/js/wiki/accessible.js b/lms/static/js/wiki/accessible.js
index 90a647ceaa..beb28082ac 100644
--- a/lms/static/js/wiki/accessible.js
+++ b/lms/static/js/wiki/accessible.js
@@ -1,11 +1,11 @@
/* By default, CodeMirror turns tabs into indents, which makes it difficult for keyboard-only
- users to "tab through" elements on a page. Including this file and setting keyMap to
+ users to "tab through" elements on a page. Including this file and setting keyMap to
"accessible" removes the "tab" from CodeMirror's default KeyMap to remedy this problem */
(function() {
- var keyMap = CodeMirror.keyMap.accessible = {
- "Tab": false,
- "Shift-Tab": false,
- fallthrough: "default"
- };
+ var keyMap = CodeMirror.keyMap.accessible = {
+ 'Tab': false,
+ 'Shift-Tab': false,
+ fallthrough: 'default'
+ };
})();
diff --git a/lms/static/karma_lms.conf.js b/lms/static/karma_lms.conf.js
index 75bd7b9322..0c48fa9784 100644
--- a/lms/static/karma_lms.conf.js
+++ b/lms/static/karma_lms.conf.js
@@ -54,6 +54,6 @@ var options = {
]
};
-module.exports = function (config) {
+module.exports = function(config) {
configModule.configure(config, options);
};
diff --git a/lms/static/karma_lms_coffee.conf.js b/lms/static/karma_lms_coffee.conf.js
index e65d9890ee..325bb7a92e 100644
--- a/lms/static/karma_lms_coffee.conf.js
+++ b/lms/static/karma_lms_coffee.conf.js
@@ -67,6 +67,6 @@ var options = {
]
};
-module.exports = function (config) {
+module.exports = function(config) {
configModule.configure(config, options);
};
diff --git a/lms/static/lms/js/build.js b/lms/static/lms/js/build.js
index 7579e00a7e..c774837178 100644
--- a/lms/static/lms/js/build.js
+++ b/lms/static/lms/js/build.js
@@ -162,4 +162,5 @@
*/
logLevel: 1
};
-}())
+}()) // eslint-disable-line semi
+// A semicolon on the line above will break the requirejs optimizer
diff --git a/lms/static/lms/js/preview/preview_factory.js b/lms/static/lms/js/preview/preview_factory.js
index 7def8f75c3..c8beba6282 100644
--- a/lms/static/lms/js/preview/preview_factory.js
+++ b/lms/static/lms/js/preview/preview_factory.js
@@ -1,10 +1,9 @@
-;(function(define) {
+(function(define) {
'use strict';
define(['jquery', 'common/js/components/utils/view_utils'],
function($, ViewUtils) {
return function(options) {
-
var $selectElement = $('.action-preview-select'),
$userNameElement = $('.action-preview-username'),
$userNameContainer = $('.action-preview-username-container');
diff --git a/lms/static/lms/js/require-config.js b/lms/static/lms/js/require-config.js
index 4630b7af32..741aefd58f 100644
--- a/lms/static/lms/js/require-config.js
+++ b/lms/static/lms/js/require-config.js
@@ -1,20 +1,20 @@
-;(function(require, define) {
+(function(require, define) {
'use strict';
// We do not wish to bundle common libraries (that may also be used by non-RequireJS code on the page
// into the optimized files. Therefore load these libraries through script tags and explicitly define them.
// Note that when the optimizer executes this code, window will not be defined.
if (window) {
- var defineDependency = function (globalName, name, noShim) {
+ var defineDependency = function(globalName, name, noShim) {
var getGlobalValue = function(name) {
- var globalNamePath = name.split('.'),
- result = window,
- i;
- for (i = 0; i < globalNamePath.length; i++) {
- result = result[globalNamePath[i]];
- }
- return result;
- },
+ var globalNamePath = name.split('.'),
+ result = window,
+ i;
+ for (i = 0; i < globalNamePath.length; i++) {
+ result = result[globalNamePath[i]];
+ }
+ return result;
+ },
globalValue = getGlobalValue(globalName);
if (globalValue) {
if (noShim) {
diff --git a/lms/static/lms/js/spec/main.js b/lms/static/lms/js/spec/main.js
index 5c4d42cf96..f7a8066c08 100644
--- a/lms/static/lms/js/spec/main.js
+++ b/lms/static/lms/js/spec/main.js
@@ -391,7 +391,7 @@
'underscore.string',
'edx-ui-toolkit/js/utils/html-utils',
'edx-ui-toolkit/js/utils/string-utils'
- ], function (_, str, HtmlUtils, StringUtils) {
+ ], function(_, str, HtmlUtils, StringUtils) {
window._ = _;
window._.str = str;
window.edx = edx || {};
diff --git a/lms/static/lms/js/spec/main_requirejs_coffee.js b/lms/static/lms/js/spec/main_requirejs_coffee.js
index c305f44cda..8b6098fecf 100644
--- a/lms/static/lms/js/spec/main_requirejs_coffee.js
+++ b/lms/static/lms/js/spec/main_requirejs_coffee.js
@@ -4,16 +4,16 @@
// into the optimized files. Therefore load these libraries through script tags and explicitly define them.
// Note that when the optimizer executes this code, window will not be defined.
if (window) {
- var defineDependency = function (globalName, name, noShim) {
+ var defineDependency = function(globalName, name, noShim) {
var getGlobalValue = function(name) {
- var globalNamePath = name.split('.'),
- result = window,
- i;
- for (i = 0; i < globalNamePath.length; i++) {
- result = result[globalNamePath[i]];
- }
- return result;
- },
+ var globalNamePath = name.split('.'),
+ result = window,
+ i;
+ for (i = 0; i < globalNamePath.length; i++) {
+ result = result[globalNamePath[i]];
+ }
+ return result;
+ },
globalValue = getGlobalValue(globalName);
if (globalValue) {
if (noShim) {
@@ -24,23 +24,22 @@
}
}
else {
- console.error("Expected library to be included on page, but not found on window object: " + name);
+ console.error('Expected library to be included on page, but not found on window object: ' + name);
}
};
- defineDependency("jQuery", "jquery");
- defineDependency("jQuery", "jquery-migrate");
- defineDependency("_", "underscore");
+ defineDependency('jQuery', 'jquery');
+ defineDependency('jQuery', 'jquery-migrate');
+ defineDependency('_', 'underscore');
}
requirejs.config({
baseUrl: '/base/',
paths: {
- "moment": "xmodule_js/common_static/js/vendor/moment.min",
- "draggabilly": "xmodule_js/common_static/js/vendor/draggabilly",
+ 'moment': 'xmodule_js/common_static/js/vendor/moment.min',
+ 'draggabilly': 'xmodule_js/common_static/js/vendor/draggabilly',
'edx-ui-toolkit': 'edx-ui-toolkit'
},
- "moment": {
- exports: "moment"
+ 'moment': {
+ exports: 'moment'
}
});
-
}).call(this, RequireJS.requirejs, RequireJS.define);
diff --git a/lms/static/lms/js/xblock/lms.runtime.v1.js b/lms/static/lms/js/xblock/lms.runtime.v1.js
index 362c760b2a..6f8e14a5f8 100644
--- a/lms/static/lms/js/xblock/lms.runtime.v1.js
+++ b/lms/static/lms/js/xblock/lms.runtime.v1.js
@@ -23,7 +23,6 @@
this.LmsRuntime = {};
this.LmsRuntime.v1 = (function(_super) {
-
__extends(v1, _super);
function v1() {
@@ -51,6 +50,5 @@
};
return v1;
-
})(XBlock.Runtime.v1);
}).call(this, URI);