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
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 );
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With