I've been trying to achieve something in javascript and have been unsuccessful. Take a look at the following object
app.Behaviors.pageColor = {
color: 'red',
height: '200px',
width: "200px",
init: function(){
$("div").css({
background: this.color,
height: this.height,
width: this.width
});
}
};
this is just a dummy object, but there are two things i can't get it to do. First, instead of $("div").css(); I'd like to have a variable that is the container the js is invoked on. Second, I'd like the init function to run without calling it... so if the data-behavior attribute is matched and the js is add'ed to my behaviours, it will run the init function. To explain my behaviours talk, this is how all my JS comes together.
// Create the object
var app = window.app || {};
// Create the Behaviors object to store methods
app.Behaviors = {}
// Creates methods of the Behaviors object
app.LoadBehavior = function(context){
if(context === undefined){
context = $(document);
}
context.find("*[data-behavior]").each(function(){
var me = $(this);
var behaviors = me.attr('data-behavior');
$.each(behaviors.split(" "), function(index,behaviorName){
try{
var BehaviorClass = app.Behaviors[behaviorName];
var initalizedBehavior = new BehaviorClass(me);
}
catch(e){
// No Operation
}
}); // each
}); // find
}; // LoadBehavior function
// Call the ready function
$(document).ready(function(){
app.LoadBehavior();
/*** Call this init when the behavior is found, not by declaring it here. ***/
app.Behaviors.pageColor.init();
//Debugging
console.log(app);
});
So this creates a Behaviours object for me to access, based on what data-behavoirs attributes it finds.
Please ask if you have any questions or need more info. Thanks!