Last active
August 29, 2015 14:14
-
-
Save sunnysideup/bd263a0aefacd4a5aa12 to your computer and use it in GitHub Desktop.
Silverstripe jQuery javascript example
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
/** | |
* usage: | |
* PHP: | |
* Requirements::javascript("mymodules/javascript/MyJSFx.js"); | |
* Requirements::customScript(" | |
* var MyObject = new MyJSFx('MyForm') | |
* .setVar('mySelector', '.foo') | |
* .setVar('myMethod', function(){return "custom foo"};) | |
* .init();", | |
* "MyObjectCustomScript" | |
* ); | |
* | |
* @param String RootSelector - e.g. MyForm as in <form id="MyForm"> or <div id="MyDiv"> | |
* | |
*/ | |
var MyJSFx = function(RootSelector) { | |
/** | |
* holds all the functions and variables | |
* | |
*/ | |
var CoreMethodsAndVariablesObject = { | |
/** | |
* @var Boolean | |
*/ | |
debug: false, | |
/** | |
* @var String | |
*/ | |
mySelector: ".barClass", | |
/** | |
* @var jQueryObject | |
*/ | |
rootjQueryObject: RootSelector, | |
/** | |
* set up | |
* | |
*/ | |
init: function(){ | |
CoreMethodsAndVariablesObject.rootjQueryObject = jQuery("#" + CoreMethodsAndVariablesObject.rootSelector); | |
CoreMethodsAndVariablesObject.rootjQueryObject.find("li").addClass("boo"); | |
//do something, attach something, etc... | |
}, | |
/** | |
* | |
* @return String | |
*/ | |
myFunction: function(){ | |
return "hello"; | |
}, | |
/** | |
* returns a list of items selected | |
* that are not empty. | |
* @return Array | |
*/ | |
myOtherFunction: function(){ | |
//do something else | |
} | |
} | |
/******************** | |
* Public API | |
*******************/ | |
return { | |
/** | |
* get a variable from CoreMethodsAndVariablesObject | |
* @param String variableName | |
* @return this | |
*/ | |
getVar: function( variableName ) { | |
if ( CoreMethodsAndVariablesObject.hasOwnProperty( variableName ) ) { | |
return CoreMethodsAndVariablesObject[ variableName ]; | |
} | |
}, | |
/** | |
* change a variable in CoreMethodsAndVariablesObject | |
* @param String variableName | |
* @param Mixed value | |
* @return this | |
*/ | |
setVar: function(variableName, value) { | |
CoreMethodsAndVariablesObject[variableName] = value; | |
return this; | |
}, | |
/** | |
* start up method | |
* @return this | |
*/ | |
init: function(){ | |
CoreMethodsAndVariablesObject.init(); | |
return this; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One function does one thing.... don't make functions that do everything on one page. The reason for this is that you can then remove / move / edit one function (file) without affecting the other parts.