Advertisement
Guest User

Untitled

a guest
Sep 5th, 2015
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1.  
  2. // 获取 GUID 方法, from Robert Kieffer
  3. Math.guid = function () {
  4. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5. var r = Math.random() * 16|0, v = c == 'x' ? r : (r&0x3|0x8)
  6. return v.toString(16)
  7. }).toUpperCase()
  8. }
  9.  
  10. // Object.create 支持
  11. if(typeof Object.create !== 'function') {
  12. Object.create = function (o) {
  13. function F(){}
  14. F.prototype = o
  15. return new F()
  16. }
  17. }
  18.  
  19. // 辅助方法
  20. var Helpers = {
  21. clone: function (obj) {
  22. if(typeof(obj) != 'object' || obj == null) return obj
  23. var newObj = {}
  24. for(var i in obj){
  25. newObj[i] = this.clone(obj[i])
  26. }
  27. return newObj
  28. }
  29. }
  30.  
  31. // Model 构建
  32. var Model = {
  33.  
  34. // 扩展自身属性
  35. extend: function (obj) {
  36. for(attr in obj) {
  37. this[attr] = obj[attr]
  38. }
  39. },
  40.  
  41. // 扩展原型链上的属性,实例可用
  42. include: function (obj) {
  43. for(attr in obj) {
  44. this.prototype[attr] = obj[attr]
  45. }
  46. },
  47.  
  48. created: function(){
  49. // 保存记录
  50. this.record = {}
  51. },
  52.  
  53. // 实例方法
  54. prototype: {
  55. init: function(){}
  56. },
  57.  
  58. // 创建新对象,继承 Model
  59. create: function(){
  60. // object.__proto__ --> Model
  61. var object = Object.create(this)
  62. object.parent = this
  63. // object.prototype --> Model.prototype
  64. object.prototype = Object.create(this.prototype)
  65. object.created()
  66. return object
  67. },
  68.  
  69. // 创建实例,并初始化
  70. init: function(){
  71. var instance = Object.create(this.prototype)
  72. instance.parent = this
  73. // 调用 prototype.init 初始化
  74. instance.init.apply(instance, arguments)
  75.  
  76. return instance
  77. }
  78.  
  79. }
  80.  
  81.  
  82. // 增加 Model 方法
  83. Model.extend({
  84. // 通过 id 查找 实例
  85. find: function (id) {
  86. var model = this.record[id]
  87. // 返回一份拷贝的 model , 避免污染原始的
  88. return Helper.clone(model)
  89. },
  90.  
  91. })
  92.  
  93. // 增加实例方法
  94. Model.include({
  95.  
  96. // 创建
  97. create: function () {
  98. // 增加记录,可查询
  99. this.id = Math.guid()
  100. this.parent.record[this.id] = this
  101. },
  102.  
  103. // 更新
  104. update: function () {
  105. this.parent.record[this.id] = this
  106. },
  107.  
  108. // 销毁
  109. destroy: function () {
  110. delete this.parent.record[this.id]
  111. },
  112.  
  113. // 保存 or 更新
  114. save: function () {
  115. this.parent.record[this.id] ? this.update() : this.create()
  116. },
  117.  
  118. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement