thinkjs / thinkjs

Use full ES2015+ features to develop Node.js applications, Support TypeScript.
https://thinkjs.org/
MIT License
5.31k stars 617 forks source link

需要扩展model #1401

Closed tangjoin closed 5 years ago

tangjoin commented 5 years ago

DESC

做轮子, 为了节省代码, 比如, model扩展统一的前置添加数据,统一的前置更新等等, 想过直接继承think.model, 然后再model目录下model文件继承自定义的扩展, 可是有一个问题, 比如model目录下,admin.js, 继承了customModel,customModel继承think.model, 可如果,admin.js和customModel,同时都需要beforeAdd, 应该如果去扩展, , 鄙人小白, 希望看到的路人可以指点

ENV

OS Platform:

Node.js Version: v8.9.1

ThinkJS Version: ^3.0.0

code

// your code here

error message

// your error message here

more description

// your detail description

lizheming commented 5 years ago
//customModel.js
module.exports = class extends think.Model {
  beforeAdd() {
    console.log('customModel');
  }
}

//admin.js
const Base = require('./customModel.js');
module.exports = class extends Base {
  beforeAdd() {
    super.beforeAdd();
    console.log('admin');
  }
}
tangjoin commented 5 years ago
//customModel.js
module.exports = class extends think.Model {
  beforeAdd() {
    console.log('customModel');
  }
}

//admin.js
const Base = require('./customModel.js');
module.exports = class extends Base {
  beforeAdd() {
    super.beforeAdd();
    console.log('admin');
  }
}

不要说我懒呀, 我的model目录下的文件都要super.beforeAdd();一下,考虑还是麻烦了点, 如果在Extend层做这个事情, 能不能把super.beforeAdd();减掉 @lizheming

lizheming commented 5 years ago

如果确认每个 model 都要写的话可以这么写,另外我觉得你不是懒,是代码写的还是太少了...

//customModel.js
module.exports = class extends think.Model {
  beforeAdd() {
    console.log('customModel');
    if(think.isFunction(this.beforeAdd2)) { this.beforeAdd2(); }
  }
}

//admin.js
const Base = require('./customModel.js');
module.exports = class extends Base {
  beforeAdd2() {
    console.log('admin');
  }
}
tangjoin commented 5 years ago

如果确认每个 model 都要写的话可以这么写,另外我觉得你不是懒,是代码写的还是太少了...

//customModel.js
module.exports = class extends think.Model {
  beforeAdd() {
    console.log('customModel');
    if(think.isFunction(this.beforeAdd2)) { this.beforeAdd2(); }
  }
}

//admin.js
const Base = require('./customModel.js');
module.exports = class extends Base {
  beforeAdd2() {
    console.log('admin');
  }
}

学习了, 还要多写代码, 扩展思路,

lizheming commented 5 years ago

是的,那我先关闭 issue 了,有问题可以继续提。