How to add a custom method to the base model?

I 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 would prefer not to use _.bindAll() .

I edited the code above to show that I am trying to associate func with only one model. A model is initialized when it is added to the collection: all models start at the same time, and I just want to associate func with one of them.

+4
source share
4 answers

Any reason not to make it obvious?

 Model = Backbone.Model.extend({ func: function() { }, }) 
+13
source

Assign func as a property of your model in your if block.

 var Model = Backbone.Model.extend({ initialize:function() { if (this.get('id') === 1) { this.func = function() { // your logic here }; this.on('func',this.func,this); } } }); 
+3
source

Static methods must be declared in the second dictionary inside the .extend call:

 SomeModel = Backbone.Model.extend({ initialize: function(){} },{ someStaticFunction: function(){ //do something } }); 

http://danielarandaochoa.com/backboneexamples/blog/2013/11/13/declaring-static-methods-with-backbone-js/

+1
source

Try the following:

 SomeModel = Backbone.Model.extend({ initialize: function(){}, someFunction: function(){ //do something } }); 

And this:

 var model = new SomeModel(); model.someFunction(); 
0
source

Source: https://habr.com/ru/post/1498027/


All Articles