Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 获取 GUID 方法, from Robert Kieffer
- Math.guid = function () {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- var r = Math.random() * 16|0, v = c == 'x' ? r : (r&0x3|0x8)
- return v.toString(16)
- }).toUpperCase()
- }
- // Object.create 支持
- if(typeof Object.create !== 'function') {
- Object.create = function (o) {
- function F(){}
- F.prototype = o
- return new F()
- }
- }
- // 辅助方法
- var Helpers = {
- clone: function (obj) {
- if(typeof(obj) != 'object' || obj == null) return obj
- var newObj = {}
- for(var i in obj){
- newObj[i] = this.clone(obj[i])
- }
- return newObj
- }
- }
- // Model 构建
- var Model = {
- // 扩展自身属性
- extend: function (obj) {
- for(attr in obj) {
- this[attr] = obj[attr]
- }
- },
- // 扩展原型链上的属性,实例可用
- include: function (obj) {
- for(attr in obj) {
- this.prototype[attr] = obj[attr]
- }
- },
- created: function(){
- // 保存记录
- this.record = {}
- },
- // 实例方法
- prototype: {
- init: function(){}
- },
- // 创建新对象,继承 Model
- create: function(){
- // object.__proto__ --> Model
- var object = Object.create(this)
- object.parent = this
- // object.prototype --> Model.prototype
- object.prototype = Object.create(this.prototype)
- object.created()
- return object
- },
- // 创建实例,并初始化
- init: function(){
- var instance = Object.create(this.prototype)
- instance.parent = this
- // 调用 prototype.init 初始化
- instance.init.apply(instance, arguments)
- return instance
- }
- }
- // 增加 Model 方法
- Model.extend({
- // 通过 id 查找 实例
- find: function (id) {
- var model = this.record[id]
- // 返回一份拷贝的 model , 避免污染原始的
- return Helper.clone(model)
- },
- })
- // 增加实例方法
- Model.include({
- // 创建
- create: function () {
- // 增加记录,可查询
- this.id = Math.guid()
- this.parent.record[this.id] = this
- },
- // 更新
- update: function () {
- this.parent.record[this.id] = this
- },
- // 销毁
- destroy: function () {
- delete this.parent.record[this.id]
- },
- // 保存 or 更新
- save: function () {
- this.parent.record[this.id] ? this.update() : this.create()
- },
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement