[英]How do I add a custom method to a backbone model?
I've tried: 我试过了:
initialize: function() {
if (this.get("id") == "modelOfInterest") {
var func = function() {
//do some stuff with the model
}
_.bind(func, this)
}
}
and 和
initialize: function() {
if (this.get("id") == "modelOfInterest") {
var func = function() {
//do some stuff with the model
}
this.on("func", func, this);
}
}
However in both cases: 但是在这两种情况下:
myModelInstance.func(); //object has no method func
I'd prefer not to use _.bindAll()
. 我宁愿不使用
_.bindAll()
。
I've edited the code above to show that I am trying to bind func to only one model. 我编辑了上面的代码,表明我试图将func绑定到只有一个模型。 The model is initialize when it is added to a collection : all the models fire initialize at the same time and I just want to bind func to one of them.
将模型添加到集合时进行初始化:所有模型同时触发初始化,我只想将func绑定到其中一个模型。
Any reason not to do the obvious? 有什么理由不明白吗?
Model = Backbone.Model.extend({
func: function() {
},
})
Assign func
as a property of your model in your if
block. 在
if
块中将func
指定为模型的属性。
var Model = Backbone.Model.extend({
initialize:function() {
if (this.get('id') === 1) {
this.func = function() {
// your logic here
};
this.on('func',this.func,this);
}
}
});
Static methods should be declared on a second dictionary within the .extend call: 应该在.extend调用中的第二个字典上声明静态方法:
SomeModel = Backbone.Model.extend({
initialize: function(){}
},{
someStaticFunction: function(){
//do something
}
});
http://danielarandaochoa.com/backboneexamples/blog/2013/11/13/declaring-static-methods-with-backbone-js/ http://danielarandaochoa.com/backboneexamples/blog/2013/11/13/declaring-static-methods-with-backbone-js/
Try this: 尝试这个:
SomeModel = Backbone.Model.extend({
initialize: function(){},
someFunction: function(){
//do something
}
});
And this: 和这个:
var model = new SomeModel();
model.someFunction();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.