Skip to content

Instantly share code, notes, and snippets.

@sunnysideup
Last active August 29, 2015 14:14
Show Gist options
  • Save sunnysideup/bd263a0aefacd4a5aa12 to your computer and use it in GitHub Desktop.
Save sunnysideup/bd263a0aefacd4a5aa12 to your computer and use it in GitHub Desktop.
Silverstripe jQuery javascript example
/**
* 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;
}
}
}
@sunnysideup
Copy link
Author

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.

  • limited pollution of global name space
  • nicely packaged
  • ability to replace variables and methods
  • ability to get the value of "private" variables and methods
  • ability to run more than one instance on a page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment