patternjavascriptMinor
Correct way to extend Bootstrap Modal - lock, unlock
Viewed 0 times
modalextendbootstrapwaycorrectunlocklock
Problem
I'm trying to extend bootstrap 3 modal window with ability to disable closing it.
I've built this code:
Working demo
After clicking "lock," you won't be able to close modal until you click "unlock."
It this way of extending bootstrap modal correct? What are potential dangers of doing this?
And how can I make this better?
EDIT:
This is my final version based on suggestions.
I've built this code:
(function ($, window, document, undefined) {
var oldHide = $.fn.modal.Constructor.prototype.hide;
$.fn.modal.Constructor.prototype.hide = function (_relatedTarget) {
if (this.isLocked) return;
return oldHide.call(this, _relatedTarget);
};
$.fn.modal.Constructor.prototype.lock = function (_relatedTarget) {
this.isLocked = true;
e = $.Event('lock.bs.modal', {
relatedTarget: _relatedTarget
});
this.$element.trigger(e);
};
$.fn.modal.Constructor.prototype.unlock = function (_relatedTarget) {
this.isLocked = false;
e = $.Event('unlock.bs.modal', {
relatedTarget: _relatedTarget
});
this.$element.trigger(e);
};
})(jQuery, window, document);Working demo
After clicking "lock," you won't be able to close modal until you click "unlock."
It this way of extending bootstrap modal correct? What are potential dangers of doing this?
And how can I make this better?
EDIT:
This is my final version based on suggestions.
Solution
Looks fine to me, except that you failed declare the
With a little bit of cleanup:
e variable in the lock/unlock functions. So it's an automatic global, which isn't good.With a little bit of cleanup:
(function ($) {
var _original = $.fn.modal.Constructor.prototype.hide;
function trigger(target, name, relatedTarget) {
target.trigger($.Event(name, { relatedTarget: relatedTarget }));
}
$.extend($.fn.modal.Constructor.prototype, {
hide: function (_relatedTarget) {
if (this.isLocked) return;
return _original.call(this, _relatedTarget);
},
lock: function (_relatedTarget) {
this.isLocked = true;
trigger(this.$element, 'lock.bs.modal', _relatedTarget);
},
unlock: function (_relatedTarget) {
this.isLocked = false;
trigger(this.$element, 'unlock.bs.modal', _relatedTarget);
}
});
})(jQuery);Code Snippets
(function ($) {
var _original = $.fn.modal.Constructor.prototype.hide;
function trigger(target, name, relatedTarget) {
target.trigger($.Event(name, { relatedTarget: relatedTarget }));
}
$.extend($.fn.modal.Constructor.prototype, {
hide: function (_relatedTarget) {
if (this.isLocked) return;
return _original.call(this, _relatedTarget);
},
lock: function (_relatedTarget) {
this.isLocked = true;
trigger(this.$element, 'lock.bs.modal', _relatedTarget);
},
unlock: function (_relatedTarget) {
this.isLocked = false;
trigger(this.$element, 'unlock.bs.modal', _relatedTarget);
}
});
})(jQuery);Context
StackExchange Code Review Q#51925, answer score: 8
Revisions (0)
No revisions yet.