Skip to content

Instantly share code, notes, and snippets.

@ethyde
Created September 30, 2014 12:17
Show Gist options
  • Select an option

  • Save ethyde/bc492766bf2c05da2489 to your computer and use it in GitHub Desktop.

Select an option

Save ethyde/bc492766bf2c05da2489 to your computer and use it in GitHub Desktop.
/*
This javascript is the main javascript for the sites actions.
*/
// --------------------------------------------------------------------------------------------------------------
// set up a master object
var UI_NAMESPACE = window.UI_NAMESPACE || {};
// set up some objects within the master one, to hold my functions and behaviors
UI_NAMESPACE.Behaviors = {};
UI_NAMESPACE.Functions = {};
// look through the document (or ajax'd in content if "context" is defined) to look for "data-behavior" attributes.
// Initialize a new instance of the method if found, passing through the element that had the attribute
// So in this example it will find 'data-behavior="show_articles"' and run the show_articles method.
UI_NAMESPACE.LoadBehavior = function(context){
'use strict';
if(context === undefined){
context = $(document);
}
context.find('*[data-behavior]').each(function(){
var that = $(this);
var behaviors = that.attr('data-behavior');
$.each(behaviors.split(","), function(index,behaviorName){
try {
var BehaviorClass = UI_NAMESPACE.Behaviors[behaviorName];
var initializedBehavior = new BehaviorClass(that);
}
catch(err){
// error statement
// alert(err.message);
}
});
});
};
// set up and trigger looking for the behaviors on DOM ready
UI_NAMESPACE.onReady = function(){
UI_NAMESPACE.LoadBehavior();
};
$(document).ready(function(){
UI_NAMESPACE.onReady();
});
UI_NAMESPACE.Behaviors.behavior_name = function(container){
// container is the element that had the data-attribute, it is passed through from application.js when initializing the behavior
// call a function inside behavior
UI_NAMESPACE.Functions.function_name(arg1, arg2);
};
UI_NAMESPACE.Functions.function_name = function(arg1, arg2){
// some set up var(s) and work with.
var some_var;
// return the result, in this example, back to show behavior_name.js
return some_var;
};
<section id="features" data-behavior="behavior_name">...</section>
<!-- if multiple behavior there are comma separated -->
<section id="features" data-behavior="behavior_name-1,behavior_name-2">...</section>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment