Skip to content

Commit 2734bdf

Browse files
committed
Promisify DataTable initialization
1 parent d50ba8e commit 2734bdf

File tree

1 file changed

+33
-31
lines changed

1 file changed

+33
-31
lines changed

src/Resources/assets/js/datatables.js

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
$.fn.initDataTables = function(config, options) {
1616
var root = this,
1717
config = $.extend({}, $.fn.initDataTables.defaults, config),
18-
state = '';
18+
state = ''
19+
;
1920

2021
// Load page state if needed
2122
switch (config.state) {
@@ -28,41 +29,42 @@
2829
}
2930
state = (state.length > 1 ? deparam(state.substr(1)) : {});
3031

31-
// Perform initial load
32-
$.ajax(config.url, {
33-
method: config.method,
34-
data: {
35-
_dt: config.name,
36-
_init: true
37-
}
38-
}).done(function(data) {
39-
var rebuild = true, cached;
32+
return new Promise((fulfill, reject) => {
33+
// Perform initial load
34+
$.ajax(config.url, {
35+
method: config.method,
36+
data: {
37+
_dt: config.name,
38+
_init: true
39+
}
40+
}).done(function(data) {
41+
var rebuild = true, cached;
4042

41-
var dtOpts = $.extend({}, data.options, config.options, options, {
42-
ajax: function (request, drawCallback, settings) {
43-
if (rebuild) {
44-
data.draw = request.draw;
45-
drawCallback(data);
46-
rebuild = false;
47-
} else {
48-
request._dt = config.name;
49-
$.ajax(config.url, {
50-
method: config.method,
51-
data: request
52-
}).done(function(data) {
43+
var dtOpts = $.extend({}, data.options, config.options, options, {
44+
ajax: function (request, drawCallback, settings) {
45+
if (rebuild) {
46+
data.draw = request.draw;
5347
drawCallback(data);
54-
})
48+
rebuild = false;
49+
} else {
50+
request._dt = config.name;
51+
$.ajax(config.url, {
52+
method: config.method,
53+
data: request
54+
}).done(function(data) {
55+
drawCallback(data);
56+
})
57+
}
5558
}
56-
}
57-
});
59+
});
5860

59-
root.html(data.template);
60-
var dt = $('table', root).DataTable(dtOpts);
61-
}).fail(function(err) {
62-
console.error(err);
61+
root.html(data.template);
62+
fulfill(dt = $('table', root).DataTable(dtOpts));
63+
}).fail(function(err) {
64+
console.error(err);
65+
reject(err);
66+
});
6367
});
64-
65-
return this;
6668
};
6769

6870
/**

0 commit comments

Comments
 (0)