Last active
December 10, 2015 19:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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