Backbone.js
A JavaScript library that provides helpful types for building and organizing rich JavaScript interfaces.
Backbone.js defination :
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Including Backbone.js in your webpage.
1 |
1 2 3 |
[php]<script type="text/javascript" src="jquery-1.7.2.js"></script> <script type="text/javascript" src="underscore.js"></script> <script type="text/javascript" src="backbone.js"></script>[/php] |
1 |
Defining a empty model in Backbone.js
1 |
[php]var Rectangle = Backbone.Model.extend({});[/php] |
Here Rectangle is new Backbone Model with no key value.We can specify any default key and value as per requirement.
Creating an new instance of model.
1 2 3 4 5 6 7 8 |
[php]var rectangleOne= new Rectangle({ width:100, height:50, position:{ x:300, y:150 } });[/php] |
Here rectangleOne is object with property i.e Key,Value Map.In this case width,height etc are the keys and 100,50,’#FFF352′ are respective values.
Creating Views in Backbone.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
[php]var RectangleView =Backbone.View.extend({ tagName: 'div', className:'rectangle', events:{ 'click':'moveColor' }, render: function(){ this.setDimension(); this.setPosition(); this.setColor(); return this; }, setPosition:function(){ var position = this.model.get('position'); this.$el.css({ left: position.x, top:position.y });}, setDimension: function(){ this.$el.css({ width:this.model.get('width') + 'px', height:this.model.get('height') + 'px' }); }, setColor : function(){ this.$el.css({'background-color': this.model.get('color')});}, moveColor:function() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++ ) { color += letters[Math.round(Math.random() * 15)]; } this.$el.css('left',this.$el.position().left + 10); this.$el.css({'background-color': color}); } }); [/php] |
Rending View to a specific tag:
1 2 |
[php]var myView = new RectangleView({model: rectangleOne}); $('div#canvas').append(rectangleOne.render().el);[/php] |
Recent Comments