Skip to content

Instantly share code, notes, and snippets.

@pstjvn
Last active September 28, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pstjvn/8a1d184e4f5af2c986e2 to your computer and use it in GitHub Desktop.
Save pstjvn/8a1d184e4f5af2c986e2 to your computer and use it in GitHub Desktop.
Control delegation pattern

Main idea: separate the business logic from the underlying dom structure and bind execution to structure separately.

Benefits:

  • changes to DOM structure can be logically separated and execute from business logic changes
  • business logic changes do not rely on DOM strcuture (stability of business logic)
  • binding can be executed in any technology or mix of technologies
  • tests can be implemented for important business logic more easily as it is not bound to DOM.
// Listen for events / binding to DOM - if DOM changes change the selector only.
$('body').on('click', '#custom.dom[selector]', function(event) {
console.log(event.target); // The actual element that fired the event.
// call my business logic, operate on local dom
});
// Listen for events from business logic / updates, validation, xhr etc.
$(document).on('MyCustomEvent', function(event, data) {
// handle custom events - split logic here to match event names.
// Target will always be document as abstract objects trigger there (assuming no access to local DOM)
});
// Implement functionlity on top of abstraction
function checkAvailability(userid, usertype, cb) {
/// implementation for XHR + read state
var result = true; // boolean result of check
cb(result);
}
function ModelType() {
this.a = ''; /// structured data / JSON.
// Also supports custom events! Data and business logic CAN and MAY emit events!!!
this.triggerMyEvent(0);
}
// Support custom events for business to local DOM (xhrs, data updates, validation etc)
ModelType.prototype.triggerMyEvent = function(data) {
// See http://api.jquery.com/trigger/
$(document).trigger('MyCustomEvent', data);
};
function updateDOM(baseElement, data) {
// Perform DOM updates (insertions/deletions) based on data.
// Should check local DOM when needed.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment