Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone render return this

Tags:

I'm trying to figure out some of the 'patterns' to set up a Backbone-project. In the examples below, in the 'render'-function, the author returns an instance of 'this'.

Why is this? Is it specific for the example, or something common for Backbone? I don't see why one should return 'this' in the 'render'-function.

The examples

http://backbonefu.com/2011/08/filtering-a-collection-in-backbone-js/

Calling a jQuery plugin in a Backbone render method

like image 391
ndequeker Avatar asked Jun 30 '12 14:06

ndequeker


2 Answers

This is just a common practice so you can call render() and to chain another method call.

It is a common pattern that the Views don't insert its HTML content in the page, and this job is done by the instance that instantiate the View in a first place.

Then what you have to write in the code that instantiate the View is something like this:

var myView = new MyView({ model: myModel }); myView.render(); $(myDOMElement).html( myView.el ); 

But if render() returns the View itself you can write the above code like this:

var myView = new MyView({ model: myModel }); $(myDOMElement).html( myView.render().el ); 
like image 195
fguillen Avatar answered Sep 21 '22 21:09

fguillen


The meaning of returning this, is for providing chaining possibilities.

For example, lets assume:

 var obj = {       prop1 : 0,       method1 : function(){       },       method2 : function(){       }  };  //Then you could do something like:  obj.method1();  obj.method2();  obj.prop1 = 1; 

All actions on obj you need to do separately.

Now consider:

 var obj = {       prop1 : 0,       method1 : function(){           return this;       },       method2 : function(){           return this;       }  };  //Now you could do these  obj.method1().prop1 = 1;  obj.method1().method2().method1(); 
like image 28
Engineer Avatar answered Sep 21 '22 21:09

Engineer