summaryrefslogtreecommitdiffstats
path: root/theme/javascript/core/exercise.js
blob: db278b8a4ab0a74c21a1bd0261f69fe997cfb22b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
define([
    "jQuery",
    "utils/execute",
    "utils/analytic",
    "core/state"
], function($, execute, analytic, state){
    // Bind an exercise
    var prepareExercise = function($exercise) {
        var codeSolution = $exercise.find(".code-solution").text();
        var codeValidation = $exercise.find(".code-validation").text();

        var editor = ace.edit($exercise.find(".editor").get(0));
        editor.setTheme("ace/theme/tomorrow");
        editor.getSession().setUseWorker(false);
        editor.getSession().setMode("ace/mode/javascript");

        // Submit: test code
        $exercise.find(".action-submit").click(function(e) {
            e.preventDefault();

            analytic.track("exercise.submit");

            execute("javascript", editor.getValue(), codeValidation, function(err, result) {
                $exercise.toggleClass("return-error", err != null);
                $exercise.toggleClass("return-success", err == null);
                if (err) $exercise.find(".alert-danger").text(err.message || err);
            });
        });

        // Set solution
        $exercise.find(".action-solution").click(function(e) {
            e.preventDefault();

            editor.setValue(codeSolution);
            editor.gotoLine(0);
        });
    };

    // Prepare all exercise
    var init = function() {
        state().$book.find("section.exercise").each(function() {
            prepareExercise($(this));
        });
    };

    return {
        init: init,
        prepare: prepareExercise
    };
});