MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Backbone.js: Getting Deeper into Backbone Model

In this article we are going deeper in backbone.js model. This wonderful Javascript framework.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

In the previous article “introduction to backbone.js” I have shown you what backbone is and why you need it, along side with some of awesome example apps built with it. We covered the overview of core concept in backbone that is MV*, But we haven’t going in the detail code much. Today, I’m going to explain how to actually use Backbone Model. Let’s start

Backbone Logo

Figure 1: Backbone Logo

Model is a representation of data in our application, if you are familiar with object and classes in javascript, Model is as simple as object with its property and methods because indeed it’s actually a plain object extended from backbone’s core although there is a little differences we will cover in this article. What I mean is, imagine we are going to build a simple image gallery where every image has title, description, owner, date. So our Model will represent image data which has the properties I just mentioned. Let’s make it clearer.

Preparation: We are assumed to build an simple image gallery app

  • The app main data is a group of images.
  • Each image has title, description, owner and date as properties.
  • Each image can be opened, edited or deleted.

Okay, from that we can understand that our app will use image as the data, so our Model will represent image. Now create a new js file called anything you want, for example ‘app.js’ add code in the listing below then include the js file in your application after backbone.

Create A Model

Listing 1: Creating Model that represent an an image

//first, create a model
var imageModel = Backbone.Model.extend({
	// later, we can add code here
}); 
//create new image based on the model
var firstImage = new imageModel();

As shown in the listing above, to create a model, we simply extend object from Backbone Model using “Backbone.Model.extend”. We just created a model called imageModel. Afterward, we create new image based on our imageModel using “new imageModel()”. But since model doesn’t have any property so the newly created image doesn’t have any property as well. Let’s then add some properties according to our preparation.

Adding Property to Model

Listing 2: Adding property

//first, create a model
var imageModel = Backbone.Model.extend({
	// later, we can add code here
}); 
//create new image based on the model
var firstImage = new imageModel();

//set the properties using ‘model.set()’
firstImage.set(‘title’, ‘Our First Image’);
firstImage.set(‘description’,’Awesome Image taken with love’);
firstImage.set(‘owner’,’Muhammad Azamuddin’);
firstImage.set(‘date’,’25 March 2013’);

//to test the result you can use ‘model.get()’ to get the value of each property
firstImage.get(‘title’); //will return ‘Our First Image’

To set image property we use model.set(‘property’,’value’) as shown in the listing 2 we add each property using model.set(). This way is fine when we are adding a single property, but what if we want to add a group of properties at the same time rather than repeating it one by one like above example. It’s not efficient, right. Don’t worry we can use another way.

Listing 3 : Adding a group of property to a model at once

//create a model
var imageModel = Backbone.Model.extend({
		// later, we can add code here
});  

// store our image properties in variable ‘details’  as a JSON
var details = {
	title : ‘Our First Image’,
	description : ‘Awesome image taken with love’,
	owner : ‘Muhammad Azamuddin’,
	date : ’25 March 2012’
}; 
// create new image with above properties
var firstImage = new imageModel(details); 

//our image now has properties taken from the variable details, test it.
firstImage.get(‘title’); // will return ‘Our First Image’
 

To add a group of properties at once, first we store our image property as a JSON. Then store it in a variable called ‘details’. Upon the creation of new image, we place the variable ‘details’ as a parameter. So simple, uh?

Set Default Property of Model

Sometimes we want to add a default value to a model, that means if the user doesn’t submit any data, the model will not fall with empty property. For example, if user forget to enter the image title instead of having empty string of title property, we can set default title value like ‘untitled’. Let’s implement in our image gallery app.

Listing 4: Define default property of model

var imageModel = Backbone.Model.extend({
// we use ‘defaults’ to set the default property of our model, previously we let this area blank, remember?
	Defaults : {
		title : ‘untitled’,
		description : ’no description available’,
		owner : ‘anonymous’,
		date : ‘no date supplied’
}
}); 
//now create new image without any property
var firstImage = new imageModel();

//although we don’t set any property, firstImage will now have default properties
firstImage.get(‘title’); //will return ‘untitled’

Changing the value of property

To change the value of property we can use the same method when we are setting a single property, use model.set(‘property’,’new value’). Or if we want to change a group of property we can use that method but we supply a json of properties as parameter. Take a look at the listing below.

Listing 5 : Changing property’s value of Model

	
	//asume we already have firstImage with its property and value
	//change single property’s value
	firstImage.set(‘title’,’This is new Title!’);
	
	//change a group of property’s at once
	firstImage.set({title : ‘This is new Title!’, description:’Some new description’ });	

Get Property’s value of Model

We have been able to set all the property of our image, that’s great. Next, we also want to retrieve the property’s value to display it in our app interface. To get a value of property we use model.get(‘propertyname’)

Listing 6 : Get the property name of Model
	firstImage.get(‘title’) // get the image title
	firstImage.get(‘description’) // get the image description
	
	//heads up! We can not retrieve property value using dot notation as in the OOP
	firstImage.title // will not work
	firstImage.description // will not work
 

Go beyond properties

Now that we have setting up all the properties according our to preparation in the beginning of this article, we realize that the last thing in our preparation is implementing an image that can be opened, edited or deleted. These three actions are not properties, rather than it’s a methods which is a function. We can add such thing to our model as the model logic.

Listing 7 : Model’s logic

//create a model
var imageModel = Backbone.Model.extend({
	//set default values of property
	defaults: {
		title : ‘untitle’
		// next default properties here
	},
//define the methods according to our preparation
	open : function() {
		alert(‘hey you just open me!’);
},
edit : function(){
	alert(‘cool, edit me so I become the best image’);
},
delete : function() {
	alert(‘you dont like me, uh?’);
}
});

Let me explain the listing above, we create a Model using extend. Then we set the default properties like in the previous section, then we add methods such as open, edit, delete. These methods are responsible for actions that we have prepared. But now it contains alert which you can replace it with the actual code when you are really building your app. These codes are meant to get you know how model work with methods just like in normal object. To test those function see listing below.

Listing 8 : Make the model do something


//we are continuing from listing 7
var firstImage = new imageModel();

firstImage.open();	//will alert ‘hey you just open me!’
firstImage.edit();	// will alert ‘cool, edit me so I become the best image’
firstImage.delete();	//will alert ‘you dont like me, uh?’

Now we have covered some of the important things to use model in backbone, but remember backbone model has so many builts-in function that you can call it without defining it first. I will list some of them here.

  • model.escape(): Similar to get, but returns the HTML-escaped version of a model's attribute. If you're interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks.
  • model.has(): Returns true if the attribute is set to a non-null or non-undefined value.
  • model.save(): Save your model to database of you persisting layer.
  • model.destroy(): Destroys the model on the server by delegating an HTTP DELETE request to Backbone.sync.

You can read the full list of these amazing functionality here http://backbonejs.org/#Model

Thank you and see you next time!



A passionate and visionary web developer who falls in love with web technologies. Always excited to learn more, just like you.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login