model.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * 简化版本的 backbone 的model
  3. *
  4. * <pre>
  5. * 作者:hugh zhuang
  6. * 邮箱:3378340995@qq.com
  7. * 日期:2018-07-02-下午3:29:34
  8. * 版权:广州流辰信息技术有限公司
  9. * </pre>
  10. */
  11. import _ from 'lodash'
  12. const Model = function(attributes, options) {
  13. var attrs = attributes || {}
  14. options || (options = {})
  15. this.attributes = {}
  16. if (options.parse) attrs = this.parse(attrs, options) || {}
  17. attrs = _.defaults({}, attrs, _.result(this, 'defaults'))
  18. this.set(attrs, options)
  19. this.initialize.apply(this, arguments)
  20. }
  21. // Model prototype
  22. _.extend(Model.prototype, {
  23. // Get the value of an attribute.
  24. get: function(attr) {
  25. return this.attributes[attr]
  26. },
  27. // Set a hash of model attributes on the object
  28. set: function(key, val, options) {
  29. var attr, attrs, option
  30. if (key == null) return this
  31. // Handle both `"key", value` and `{key: value}` -style arguments.
  32. if (typeof key === 'object') {
  33. attrs = key
  34. options = val
  35. } else {
  36. (attrs = {})[key] = val
  37. }
  38. options || (options = {})
  39. var current = this.attributes
  40. for (attr in attrs) {
  41. current[attr] = attrs[attr]
  42. }
  43. if (!_.isEmpty(options)) {
  44. for (option in options) {
  45. current[option] = options[option]
  46. }
  47. }
  48. return this
  49. }
  50. })
  51. var extend = function(protoProps, staticProps) {
  52. var parent = this
  53. var child
  54. // The constructor function for the new subclass is either defined by you
  55. // (the "constructor" property in your `extend` definition), or defaulted
  56. // by us to simply call the parent's constructor.
  57. if (protoProps && _.has(protoProps, 'constructor')) {
  58. child = protoProps.constructor
  59. } else {
  60. child = function() { return parent.apply(this, arguments) }
  61. }
  62. // Add static properties to the constructor function, if supplied.
  63. _.extend(child, parent, staticProps)
  64. // Set the prototype chain to inherit from `parent`, without calling
  65. // `parent`'s constructor function.
  66. var Surrogate = function() { this.constructor = child }
  67. Surrogate.prototype = parent.prototype
  68. child.prototype = new Surrogate()
  69. // Add prototype properties (instance properties) to the subclass,
  70. // if supplied.
  71. if (protoProps) _.extend(child.prototype, protoProps)
  72. // Set a convenience property in case the parent's prototype is needed
  73. // later.
  74. child.__super__ = parent.prototype
  75. return child
  76. }
  77. Model.extend = extend
  78. export default Model