javascript - Bootstrap stateful button not working as expected -
i trying bootstrap button show "loading..." while time consuming function (fetching data external source) executed. interestingly, reference implementation using settimeout
works perfectly.
it seems me somehow $(button).button('loading')
command executed after function closes , settimeout works around waiting in background. how can replicate result of settimeout command code something?
jsfiddle demonstrating problem.
here html code:
<button type="button" class="btn btn-warning" id="comb" data-loading-text="loading..." autocomplete="off" onclick="comb()">combinations</button> <button class="btn btn-primary" id="timer" data-loading-text="loading..." autocomplete="off" onclick="timer()">set timeout</button>
and here javascript:
function combinations(str) { var fn = function (active, rest, a) { if (!active && !rest) return; if (!rest) { a.push(active); } else { fn(active + rest[0], rest.slice(1), a); fn(active, rest.slice(1), a); } return a; } return fn("", str, []); } function comb() { var btn = $('#comb').button('loading'); console.log(combinations('abcdefghijklmnopqrs'));//this function takes lot of time (~5s) execute btn.button('reset'); } function timer() { var btn = $('#timer').button('loading'); settimeout(function () { btn.button('reset'); }, 3000); }
i found working solution of hack. still appreciate better suggestions and/or explanatinos going on.
here html:
<button type="button" class="btn btn-warning" id="comb" data-loading-text="loading..." autocomplete="off" onclick="comb()">combinations</button>
and here working javascript (basically wrapped code in settimeout command short timeout:
function combinations(str) { var fn = function (active, rest, a) { if (!active && !rest) return; if (!rest) { a.push(active); } else { fn(active + rest[0], rest.slice(1), a); fn(active, rest.slice(1), a); } return a; } return fn("", str, []); } function comb() { var btn = $('#comb').button('loading'); settimeout(function () { console.log(combinations('abcdefghijklmnopqrs')); btn.button('reset'); },100); }
it seems me, code executing preventing bootstraps javascript (or jquery) changing button state until finished. settimeout command gives bootstraps javascript time change button state before code executed. still find strange , appreciate explanation.
edit:
here jsfiddle demonstrating solution
edit2: realized timeout of 100 ms safer 10ms because slower devices/browsers might not able rebuild page in 10ms. updated code/jsfiddle accordingly.
edit3: peterblazejevicz on @ the bootstrap github issue tracker, found elegant solution using promise:
function comb() { var btn = $('#promise').button('loading'); var request = $.ajax('/'); request.done(function (data) { console.log(combinations('abcdefghijklmnopqrs')); }); request.always(function () { btn.button('reset'); }); }
Comments
Post a Comment