Last active
August 29, 2015 14:08
-
-
Save impressiver/77fd021211975c3e66ff to your computer and use it in GitHub Desktop.
Angular/jQuery event wrappers
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
/****************************************************************************** | |
* | |
* Adapter functions to deal w/ Angular <--> jQuery (custom) events | |
* | |
* I wrote these quickly just to see if they'd fly. They should really be added | |
* to a provider, I just haven't gotten around it. | |
* | |
*****************************************************************************/ | |
/** | |
* Naturalize a jQuery event handler as an Angular citizen | |
* | |
* @example | |
* $element.on('my-plugin-event', App.immigrate($scope, function(event, data) { | |
* // executed within an Angular $digest cycle | |
* )); | |
* | |
* @param {Object} scope - Angular scope to use as the callback context | |
* @param {Function} cb - Callback executed inside the Angular world, receives | |
* the jQuery event and optional array of extra jQuery event data as params | |
* @return {Function} Wrapped callback function to use w/ `jQuery.fn.on` | |
*/ | |
App.immigrate = function (scope, cb) { | |
return function (event, extra) { | |
var fn = function() { | |
scope.$apply(cb.call(this, event, extra)); | |
}.bind(this); | |
// Guarantees $apply is executed outside of any in-progress $digest | |
setTimeout(fn, 0); | |
}; | |
}; | |
/** | |
* Export an Angular event as a jQuery event, triggering any registered jQuery | |
* event handlers on the *first* element that matches the given selector. | |
* | |
* @example | |
* $scope.$on('some-angular-event', App.emmigrate('my-plugin-event', '.my-button', [extraData])); | |
* | |
* @param {string} event - The jQuery event name to trigger | |
* @param {string|Object} selector - jQuery selector (event is fired on the | |
* first matched element only) | |
* @param {array=} extra - Optional array of additional data sent to jQuery | |
* event handlers | |
* @return {Function} Wrapped function to use as `$scope.$on` callback | |
*/ | |
App.emmigrate = function (event, selector, extra) { | |
return function () { | |
var args = Array.prototype.slice.call(arguments, 1), | |
params = [event].concat(args, extra); | |
// Using `triggerHandler` prevents event feedback chaos | |
$(selector).triggerHandler.apply(this, params); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment