Par*_*ris 2 javascript node.js backbone.js
我正在尝试向骨干添加一些功能,以便我可以与mongodb进行通信.现在我知道这对客户端不起作用; 但是,我确实喜欢骨干网服务器端模型逻辑的功能.我注意到如果我不断为每个模型添加相同的功能,我会做一堆重复工作,所以决定创建一个"app_model"文件,以便在我是服务器端时扩展主干.我也不想覆盖标准的Backbone函数,因为它们将是有用的客户端.
所以我们以此用户类为例:
var Backbone = require('./app_model');
var User = Backbone.Model.extend({
name : "users",
defaults: function() {
return {
username: "default",
role: 2,
created: new Date(),
updated: new Date(),
logged: new Date()
};
},
idAttribute: "username",
/**
* A predefined listing of user roles
*/
userRoles: [
"admin", //0
"author", //1
"user" //2
],
initialize: function() {
if(!!app) {
this.svrInit();
}
}
});
module.exports = User;
Run Code Online (Sandbox Code Playgroud)
我想通过使用我的"app_model.js"文件将函数附加到主干上,该文件当前看起来像这样:
var Backbone = require('backbone'),
Deferred = require('Deferred'),
when = Deferred.when;
Backbone.Model.prototype.svrInit = function() {
//TODO: perhaps the code below should be made static some how so we don't have a bunch of instances of collection
var model = this;
if(!!app.db){
app.db.collection(this.name,function(err,collection){
model.collection = collection;
});
}
};
Backbone.Model.prototype.svrSave = function() {
var model = this.toJSON();
var dfd = new Deferred();
this.collection.insert(model, {safe:true}, function(err, result){
dfd.resolve();
});
return dfd;
};
Backbone.Model.prototype.svrFind = function(options) {
var model = this.toJSON();
var dfd = new Deferred();
this.collection.find(options, {safe:true}, function(err, result){
dfd.resolve();
});
return dfd;
};
module.exports = Backbone;
Run Code Online (Sandbox Code Playgroud)
当我把它抽象出来时,我运行了测试,似乎工作正常.有没有更好的方法来做这些?任何坑落?我正在使用全局"app"变量,那是不是很糟糕?如果是这样的话有什么方法呢?我确实发现我不得不放在this.svrInit()模型级别的init函数中,但是无论如何都要在创建后自动生成它?
所以我一直在思考这个问题几天,而我提出的最干净的事情是这样的:
var MyModel = function( attributes, options ) {
Backbone.Model.apply( this, arguments );
this.specialInitializer();
};
MyModel.extend = Backbone.Model.extend;
_.extend( MyModel.prototype, Backbone.Model.prototype, {
specialInitializer: function() {
// called after the users 'initialize'
console.log("MyModel initialized.", this);
},
otherNewMethod: function() {
// this is just like any other instance method,
// just as if Backbone.Model implemented it
}
} );
Run Code Online (Sandbox Code Playgroud)
所以这样做基本上是一种全新的"种类" Backbone.Model.一个也叫specialInitializer.如果您在构造函数定义之后查看主干源,Backbone.Model您将看到这是一个类似的策略.
Backbone.Events,在我们的情况下Backbone.Model).您的新初始化程序当然可以调用它需要的任何其他内容等.
至于你关于静态集合内容和全局app变量的其他问题,我恐怕我没有完全按照那里发生的事情,因为我没有看到定义,app也不知道你在使用什么集合.
这是一个小提琴,通过一些额外的记录等来证明这一点.