Last active
December 29, 2015 23:59
-
-
Save GianlucaGuarini/7746905 to your computer and use it in GitHub Desktop.
Simple Model class inspired to the Backbone models.
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
/** | |
* 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); | |
} | |
}); | |
}; | |
})); |
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 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