Backbone.js is a compact library used to organize JavaScript code. It is also known as an MVC/MV* framework. MVC is merely an architecture paradigm for developing user interfaces if you are unfamiliar with it. Designing a program’s user interface is a lot easier when JavaScript functions are used. BackboneJS provides a variety of building elements to aid developers in creating client-side web applications, including models, views, events, routers, and collections.
Backbone.js view constructor is first created when the view is first made. It initializes the view. When a view is generated, it is called and uses the new keyword. It is one of a number of unique options that will be directly linked to the view. If initialize method is declared and defined inside the view, it is automatically called when a view object is created, we can call all the other functions inside this method using this keyword which will terminate the need to call them with the object reference later.
Syntax:
new View( options )
Used Parameter:
- options: This parameter is optional. It can be a lot of different values like a model, collection, id, className, tagName, attributes, and events.
Example 1: The code below shows how we can create a simple initialize function in a view.
HTML
<!DOCTYPE html> < html > < head > < title >Backbone.js constructor/initialize View</ title > type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > </ head > < body > < h1 style = "color:green;" > neveropen </ h1 > < h3 >Backbone.js constructor/initialize View</ h3 > < script type = "text/javascript" > var ViewDemo = Backbone.View.extend({ initialize:function(){ document.write( 'Hello Geek!! Welcome to neveropen.' + ' This is a computer science portal for neveropen.'); } }); var myview = new ViewDemo(); </ script > </ body > </ html > |
Output:
Example 2: The code below shows how we can manipulate HTML by using the el property. Then we need to add the content we want to add/change to the $el jQuery object. Also, we haven’t called the render function with the object reference, it is called upon by the initialize function.
HTML
<!DOCTYPE html> < html > < head > < title >Backbone.js constructor/initialize View</ title > type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > </ head > < body > < h1 style = "color: green;" > neveropen </ h1 > < h3 >Backbone.js constructor/initialize View</ h3 > < div id = "content" ></ div > < script type = "text/javascript" > var ViewDemo = Backbone.View.extend({ initialize:function(){ this.render(); }, render:function(){ this.$el.html( "Hello Geek!! Welcome to neveropen." + " This is a demo of view with using render function.") } }); var myview = new ViewDemo({ el: "#content" }); </ script > </ body > </ html > |
Output:
Reference: https://backbonejs.org/#View-constructor