Cascading function calls
Cascading function calls can be useful for building up properties on an object. We can simply return this
at the end of each cascading function so that we always end up with the object when we're done.
Example - building a flash message after an ajax request in rails:
$.ajax({
method: 'DELETE',
url: url,
contentType: 'application/json',
error: function(status, data, jqxhr){
var message = JSON.parse(status.responseText).error;
var flash = new FlashBuilder('div');
flash.text(message)
.addClass('notification-error')
.append('.flash-messages', '#some_container');
}
});
function FlashBuilder(el){
this.element = $('<' + el + '>');
this.text = function(text){
this.element.text(text);
return this;
};
this.addClass = function(klass){
this.element.addClass(klass);
return this;
};
this.append = function(target, container){
if(container){
$(container).find(target).append(this.element);
} else {
$(target).append(this.element);
}
return this;
}
}
Tweet