Created
August 19, 2013 21:46
-
-
Save andrewburgess/6274567 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define([ | |
'ko', | |
'jquery' | |
], function (ko, $) { | |
ko.bindingHandlers.notification = { | |
update: function (element, valueAccessor, allBindingsAccessor, viewModel) { | |
var rawValue = valueAccessor(), | |
//notification can be passed an object with properties 'message', 'duration', 'fadeoutDuration', 'hide', 'fade', and 'callback', or it can be given just a string | |
options = typeof rawValue == 'object' ? rawValue : { message: rawValue }, | |
message = ko.utils.unwrapObservable(options.message), | |
duration = options.duration !== undefined ? ko.utils.unwrapObservable(options.duration) : 5000, //5 seconds is default fade out | |
fadeoutDuration = options.fadeoutDuration !== undefined ? ko.utils.unwrapObservable(options.fadeoutDuration) : 200, //default is 200 ms | |
hide = options.hide !== undefined ? ko.utils.unwrapObservable(options.hide) : true, //default is to hide it | |
fade = options.fade !== undefined ? ko.utils.unwrapObservable(options.fade) : true, //default is to fade it out in presence of jquery | |
callback = options.callback !== undefined ? ko.utils.unwrapObservable(options.callback) : function () { }, | |
jQueryExists = typeof jQuery != 'undefined'; | |
//set the element's text to the value of the message | |
if (message === null || message === undefined) | |
message = ""; | |
$(element).removeClass().addClass('notification alert'); | |
if (typeof message === 'object') { | |
element.innerHTML = message.message; | |
$(element).addClass('alert-' + message['class']); | |
if (message.message == '') { | |
element.style.display = 'none'; | |
return; | |
} | |
} else { | |
element.innerHTML = message; | |
$(element).addClass('alert-info'); | |
if (message == '') { | |
element.style.display = 'none'; | |
return; | |
} | |
} | |
//clear any outstanding timeouts | |
clearTimeout(element.notificationTimer); | |
//if there are any animations going on, stop them and show the element. otherwise just show the element | |
$(element).stop(true, true).show(); | |
if (hide) { | |
//run a timeout to make it disappear | |
element.notificationTimer = setTimeout(function () { | |
//if jQuery is there, run the fadeOut, otherwise do old-timey js | |
if (fade) | |
$(element).fadeOut(fadeoutDuration, function () { | |
options.message(''); | |
callback(); | |
}); | |
else { | |
$(element).hide(); | |
options.message(''); | |
callback(); | |
} | |
}, duration); | |
} else { | |
callback(); | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment