Skip to content

Instantly share code, notes, and snippets.

@raiden-dev
Created September 17, 2012 16:33
Show Gist options
  • Save raiden-dev/3738372 to your computer and use it in GitHub Desktop.
Save raiden-dev/3738372 to your computer and use it in GitHub Desktop.
KnockoutJS Custom Binding: gaqPush
/**
* KO: Google Analytics data pusher.
* @param {array|object} Binding value.
* @config {array} GA track data.
* @config {object}
* {array} [track] GA track data.
* {string} [eventName='click'] Event name.
* @requires GA Tracker <ga.js>
* @example
* // View
* <div data-bind="gaqPush: ['_trackEvent', 'Hello']"></div>
* <div data-bind="gaqPush: {track: ['_trackEvent', 'World'], eventName: 'mouseover'}"></div>
*/
ko.bindingHandlers.gaqPush = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var isObj = ( typeof value === 'object' && !(value instanceof Array) );
var track = isObj ? value.track : value;
var eventName = isObj ? value.eventName : 'click';
var newValueAccessor = function () {
var result = {};
result[eventName] = function() {
//console.log(track);
_gaq.push(track);
}
return result;
}
ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment