Skip to content

Instantly share code, notes, and snippets.

@krasimir
Last active December 10, 2015 19:38
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 krasimir/4482625 to your computer and use it in GitHub Desktop.
Save krasimir/4482625 to your computer and use it in GitHub Desktop.
A Backbone.JS style object for creating JavaScript applications. It's purpose is to hold the business logic too. Dependencies: jQuery, underscore
var element = {
el: $("<div></div>"),
appended: [],
listeners: {},
init: function() {
return this;
},
onAppend: function() {
return this;
},
onClear: function() {
return this;
},
extend: function(obj) {
var result = _.extend({}, this, {el: $("<div></div>"), appended: []}, obj);
result.init();
return result;
},
clear: function() {
this.el.empty();
_.each(this.appended, function(elementObj) {
elementObj.clear();
});
this.appended = [];
this.onClear();
return this;
},
styles: function(props) {
props = props ? props : [];
for(var attr in props) {
this.el.css(attr, props[attr]);
}
return this;
},
append: function(elements) {
var self = this;
if(!_.isArray(elements)) {
elements = [elements];
}
_.each(elements, function(elementObj) {
self.el.append(elementObj.el);
self.appended.push(elementObj);
if(typeof elementObj.onAppend != "undefined") {
elementObj.onAppend();
}
});
return this;
},
tag: function(name) {
if(name === "img") {
this.el = $("<" + name + " />");
} else {
this.el = $("<" + name + ">" + "</" + name + ">");
}
return this;
},
template: function(id) {
var tag = $("#" + id);
if(tag.length == 0) {
alert("Template with id=" + id + " is missing.");
} else {
this.el.append($($("#" + id).html()));
}
return this;
},
on: function(eventName, callback) {
if(!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(callback);
},
dispatch: function(eventName) {
if(this.listeners[eventName]) {
var self = this;
_.each(this.listeners[eventName], function(callback) {
callback(self);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment