如何使用带有角度监视类型界面的自定义jQuery事件;
// adds a custom jQuery event which gives the previous and current values of an input on change
(function ($) {
// new event type tl_change
jQuery.event.special.tl_change = {
add: function (handleObj) {
// use mousedown and touchstart so that if you stay focused on the
// element and keep changing it, it continues to update the prev val
$(this)
.on('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
.on('change.tl_change', handleObj.selector, function (e) {
// use an anonymous funciton here so we have access to the
// original handle object to call the handler with our args
var $el = $(this);
// call our handle function, passing in the event, the previous and current vals
// override the change event name to our name
e.type = "tl_change";
handleObj.handler.apply($el, [e, $el.data('tl-previous-val'), $el.val()]);
});
},
remove: function (handleObj) {
$(this)
.off('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
.off('change.tl_change', handleObj.selector)
.removeData('tl-previous-val');
}
};
// on focus lets set the previous value of the element to a data attr
function focusHandler(e) {
var $el = $(this);
$el.data('tl-previous-val', $el.val());
}
})(jQuery);
// usage
$('.some-element').on('tl_change', '.delegate-maybe', function (e, prev, current) {
console.log(e); // regular event object
console.log(prev); // previous value of input (before change)
console.log(current); // current value of input (after change)
console.log(this); // element
});