Skip to content

Instantly share code, notes, and snippets.

@kurko
Created February 9, 2011 14:25
Show Gist options
  • Save kurko/818552 to your computer and use it in GitHub Desktop.
Save kurko/818552 to your computer and use it in GitHub Desktop.
Connects variables to callbacks, making it possible to connect JS views to models
/*
event_handler.js adds a layer for setting variables in Javascript
and calling a callback whenever it is changed.
You won't need to call a function manually to update your view.
This method makes it easy to separated view-logic from business-logic
at Javascript level, and let things run automatically.
*/
/*
In your view, set on initialization:
// first argument is the variable which will be watched.
// second is the callback.
setListener('proposal_price', ProposalView.updateStatus );
Whenever you want to set a new value to proposal_price, call:
setVar('proposal_price', new_price);
This will automatically trigger ProposalView.updateStatus().
The purpose of this code is to make your view really dynamic.
You can make an Ajax call and make the views change, just by
setting a variable.
*/
// event_handler.js
window['_obj'] = new Array();
window['listening'] = new Array();
function setVar(varName, varValue){
window['_obj'][varName] = varValue;
if( varName in listening ){
callListener(varName);
}
}
function setListener(varName, callback){
listening[varName] = callback;
}
function callListener(varName){
listening[varName]();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment