Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Last active December 29, 2015 23:59
Show Gist options
  • Save GianlucaGuarini/7746905 to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/7746905 to your computer and use it in GitHub Desktop.
Simple Model class inspired to the Backbone models.
/**
* Simple Model class to listen all its status changes
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.Model = factory();
}
}(this, function() {
return function() {
if (!jQuery)
throw 'this script needs jQuery to work properly';
return $.extend($({}), {
set: function(prop, value) {
this[prop] = value;
this.trigger('change', arguments);
this.trigger('change:' + prop, arguments);
},
get: function(prop) {
return this[prop];
},
extend: function(obj) {
return $.extend(this, obj);
}
});
};
}));
var person = new Model();
person.extend({
init: function() {
this.on('change', this.onChange);
this.on('change:surname', this.onSurnameChanged);
this.set('name', 'Johnny');
this.set('surname', 'Depp');
},
onChange: function(e, prop, val) {
console.log(e, prop, val);
console.log(this);
},
onSurnameChanged: function(e, prop, val) {
console.log('new surname' + val);
},
});
person.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment