Skip to content

Instantly share code, notes, and snippets.

@xwartz
Last active September 5, 2015 07:40
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 xwartz/c04fc41c5f470d0cad74 to your computer and use it in GitHub Desktop.
Save xwartz/c04fc41c5f470d0cad74 to your computer and use it in GitHub Desktop.
简单的 Model 实现
// 获取 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()
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment