Completed
Pull Request — develop (#179)
by Wachter
13:33
created

main.js ➔ ... ➔ compare   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
rs 8.8571
cc 5
nc 3
nop 3
1
/*
2
 * This file is part of Sulu.
3
 *
4
 * (c) MASSIVE ART WebServices GmbH
5
 *
6
 * This source file is subject to the MIT license that is bundled
7
 * with this source code in the file LICENSE.
8
 */
9
10
define(['jquery', 'text!./grid.html'], function($, gridTemplate) {
11
12
    'use strict';
13
14
    var compare = function(id, $a, $b) {
15
            var aValue = parseInt($a.find('input').val()),
16
                bValue = parseInt($b.find('input').val()),
17
                aId = $a.data('id'),
18
                bId = $b.data('id');
19
20
            if (aValue < bValue) {
21
                return -1;
22
            } else if (aValue > bValue || aId === id || bId === id) {
23
                return 1;
24
            }
25
26
            return 0;
27
        },
28
29
        highlight = function($item) {
30
            $item.addClass('highlight-animation');
31
            $item.one('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function() {
32
                $item.removeClass('highlight-animation');
33
            });
34
        },
35
36
        focus = function($item) {
37
            $item.find('input').focus();
38
        };
39
40
    return {
41
42
        defaults: {
43
            options: {
44
                pages: []
45
            },
46
            templates: {
47
                grid: gridTemplate
48
            },
49
            translations: {
50
                title: 'public.title'
51
            }
52
        },
53
54
        initialize: function() {
55
            this.render();
56
57
            this.bindDomEvents();
58
        },
59
60
        render: function() {
61
            this.$el.append(this.templates.grid({translations: this.translations, pages: this.options.pages}));
62
        },
63
64
        bindDomEvents: function() {
65
            this.$el.find('input').on('change', function(e) {
66
                this.orderTable($(e.currentTarget).parents('tr'));
67
            }.bind(this));
68
        },
69
70
        orderTable: function($item) {
71
            var id = $item.data('id'),
72
                rows = this.$el.find('tbody tr').get();
73
74
            rows.sort(function(a, b) {
75
                return compare(id, $(a), $(b));
76
            });
77
78
            $.each(rows, function(index, row) {
79
                $(row).find('input').val(index + 1);
80
81
                this.$el.find('table').children('tbody').append(row);
82
            }.bind(this));
83
84
            highlight($item);
85
            focus($item);
86
        }
87
    }
88
});
89