Category Archives: Backbone

Revision:how to use backbone

three way to create your  model:

Person = Backbone.Model.extend({})
Person = Backbone.Model.extend({
defaults:{
name:"";//Model arrow undefined data
create:new Date() //here arrow put PHP function
}
});
Person = Backbone.Model.extend({
defaults:function(){
return   {  name:"";  //Model arrow undefined data
create:new Date()
}
}
});

Read and Write:

var person = new Person({ name:”Sandy”,age:”12″});

person.get(“name”);//” Sandy”

person.set({name:”Anna”,age:”12″});//overwrite it

Create Simple View

PersonView = Backbone.View.extend({

render:function(){

var person = “<p>” + this.model.get(“user”) + “</p>”;

$(this.el).html(person);

}

});

“this.el” meaning: every View Model create a Page Scope, el means the root tag<div></div>,

Get Model data Add into HTML page

var personView = new PersonView({

model:person;

})

personView.render();

console.log(personView.el);//check the el

Get Data from the server(RESTful way)

var Person = Backbone.Model.extend({urlRoot:”/person”}); //point to the data sourse

var person = new Person({id:1}); //point to your object

person.fetch();//get /person/1

person.save();//put /person/1

var newPerson=new PersonModel(); //create a new object

newPerson.set({name:”Sandy Zhang”}); // give the an name

newPerson.save(); // insert into /person

newPerson.get(“id”); //2

newPerson.destroy();// Delete /person/2

Create Better View

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

render:function(){

var person=”<p>” + this.model.get(“name”)+”</p>”;

$(this.el).html(person);

}

});

this will render html sourse:

<article id=”personOne” class = “person” title=”Sandy Zhang”>

<p>Sandy Zhang</p>

</article>

Cache of the jQuery object

$(“#personOne”).html();

in Backbone.js: $(this.el).html(); or better way : this.$el.html()

el  is  generated for the cache of jQuery object, so that it can be used repeatedly without fear of generating multiple instances of the jQuery object.

Built-in template engine(underscore template)

use render() seems not elegant ,now we use underscore template

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

template: _.template(‘<p><%= name %></p>’),

render:function(){

data = this.model.toJSON();

$(this.el).html(template(data));

}

}); // Cool! looking better

Track your instance

var person = new Person({name:”sandy”}); //create a instance

person.on(“change”,function(){

alert(“Something changed on ” + this.get(“name”) );

});

person.on(“change:age”,function(){

alert(this.get(“name”) +”,Your age has been changed ”  );

});

Change data to JSON format

var person = new Person({id:1});

console.log(person.toJSON());

//or

console.log(JSON.stringify(person));

Now Add View event

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

template: _.template(‘<p><%= name %></p>’),

render:function(){

data = this.model.toJSON();

this.$el.html(template(data));

},

events:{ “mouseover” :”showMore”,},

showMore:function(){…….},

});

Advance Level

1.Server <= (get) model (data) => view (rendering) => DOM

var PersonView = Backbone.View.extend({

input:_.template(‘<input type=”text”><%= name%></input>’),

submit: _.template(‘<button type=”submit”>Change Name</button>’),

render: function(){

data = this.model.toJSON();

this.$el.html(input(data)).html(submit);

}

});

Now we can  change name now, the question is how do you know the model data has changed? This needs to view it through the event.

var PersonView = Backbone.View.extend({

events:{“submit button”:”updateName”}

updataName:function(){

newName = $(this).val();  // this=button!

if(newName !== this.model.get(‘name’)){

this.model.set({name:newName}); }

else{ return;}

}

});

Well…it did work, but the problem is : should belong Model processing logic  put in the View now. So we reconstruct it.

var PersonView = Backbone.View.extend({

events:{“submit button”:”updateName”}

updateName:function(){

newName = $(this).val();

this.model.updateName(newName);

}

});

var Person = Backbone.Model.extend({

updateName: function(newName){

this.set({name:newName});

this.save(); // tell server to save the new name into database

}

})

2.The above, we pass the parameter value changes transferred to the Model, and then further processed by the Model it wants to do.

Now, the loop model like this:

Server <= (updated) model (proceed) <= (notification) view <= (user interaction) DOM

If the data model changes, how to notice the view? You might immediately think of the render method can be performed immediately after the completion notification view:

var PersonView = Backbone.View.extend({

updateName:function(){

newName = $(this).val();

this.model.updateName(newName);

this.render();

}

});

Ah good idea …… but it is not always useful, because the value of the model could be changed elsewhere, such as in another view . So, how to notify the specified view  response to the model changes?

So, use listenTo() function

var PersonView = Backbone.View.extend({

initialize:function(){

this.listenTo(this.model,”change”,this.render);

//this.model.on(“change”,this.render,this);

}

});

3. collection

a)Collect multiple model data

When there was more and more instances , in order to facilitate the processing of them, we usually think of them together with the array. Backbone.js Collection module provides a simplified way to help us:

var Person = Backbone.Collection.extend({ model:person });

var person.add{[{name:”Sandy Zhang”, id:1},{name:”Anna li”,id:2}]};

person.length //=>2

person.get(2) // => { name : “Anna li”,id:2}

person.at(0) //=>{ name:”Sandy Zhang”, id:1}

HTML5 Push State API

Backbone.history.start({pushState: true});

var App = new (Backbone.Router.extend({
initialize: function() {
this.person = new person();
this.personView = new personView({collection: this.person});
$(“#app”).append(this.personView.el);
},

index: function() {
this.person.fetch();
},

start: function() {
Backbone.history.start({pushState: true});
}
}));

$(function() { App.start(); });

Backbone Collection

run the code in the browse should look like

backbone3

here is the code for get the collection:

<script type=”text/javascript”>
Student = Backbone.Model.extend({
defaults:{
name:””,
age:””
}

});
ClassRoom = Backbone.Collection.extend({
model:Student
});

var student1 = new Student({name:”Sandy”,age:”20″});
var student2 = new Student({name:”Rachel”,age:”18″});
var student3 = new Student({name:”Anna”,age:”23″});
var collection = new ClassRoom([student1,student2,student3]);

</script>

Backbone – Router

On this post create 2 template,and use backbone router to communicate with those 2 pages, here is the code.

<script type=”text/template” id=”first_template”>
<label>My First View:</label>
<a href=”#second”>Go to Second View</a>

</script>

<script type=”text/template” id=”second_template”>
<label>My Second View:</label>
<a href=”#first”>Go to First View</a>

</script>

<div id = “container”></div>

<script type=”text/javascript”>
FirstView = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#first_template’).html(),{});

this.$el.html(template);

}

});

SecondView = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#second_template’).html(),{});

this.$el.html(template);

}

});

MyRouter = Backbone.Router.extend({
routes:{
“”:”firstPage”,
“first”:”firstPage”,
“second”:”secondPage”
},

firstPage:function(){
new FirstView();
},
secondPage:function(){
new SecondView();
}

});

var router = new MyRouter();
Backbone.history.start();

</script>

 

Backbone create a View

On this post just create a event and render it, and the event communicate with your html ID.

here is the code for your view, just put this in your body will work.

test on the browser should look like this.

backbone2

<script type=”text/template” id=”sample_template”>
<label>Name:</label>
<input type=”text” id=”name_desc”/>
<input type=”button” value=”Add Name” id=”btn”/>

</script>
<div id = “container”></div>
<script type=”text/javascript”>
Name = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#sample_template’).html(),{});

this.$el.html(template);

},
events:{
“click input[type=button]”: “addName”
},

addName:function(){
alert(“The name: “+$(‘#name_desc’).val() + ”  has been added”);
}
});

var name = new Name();
</script>

Backbone setup your Model

This could put on external file or you could put in the body area, test in browser, you should see things like this

backbone1

<script type=”text/javascript”>
           //create a new model named person, if you work with PHP framework like zend framework just use the model name you create in your php files
Person = Backbone.Model.extend({
initialize: function(){
console.log(“Object is created”);

//this is for track the value weather it changed or not
this.on(“change:name”,function(){
alert(“Name attribute value has been changed”);
});
this.on(“change:age”,function(){
alert(“Age attribute value has been changed”);
});
},
defaults:{
name:”Sandy”,
gender:”Female”,
age:”20″
},
//create a customer function
getPersonInfo:function(){
document.write(“<h2>Name is: ” +this.get(‘name’)+”,Gender is : “+this.get(‘gender’)+”,Age is:”+this.get(‘age’) +”</h2>”);
}
});
//create an object name sandy
var sandy = new Person();
document.write(sandy.get(‘name’)+”<br/>”);
document.write(sandy.get(‘gender’)+”<br/>”);
document.write(sandy.get(‘age’)+”<br/>”);
//create an object name simon and give different value to name,gender, age
var simon = new Person({name:”simon”,gender:”male”,age:”12″});
document.write(simon.get(‘name’)+”<br/>”);
document.write(simon.get(‘gender’)+”<br/>”);
document.write(simon.get(‘age’));
//call the customer function
sandy.getPersonInfo();
//this set function goes to overide the name then will have alert window
sandy.set({name:”SandyZhang”});
sandy.set({age:”30″});
</script>

Set up your backbone

Set up your backbone is really ease, just down the backbone, and underscore into your local file, and the jQuery just use the google jQuery, so you just add this the link to your web page, it will fast your website(this is called CDNS: content delivery networks,common quesion for fornt-end designer interviews).

so your page’s code just like this:

<!DOCTYPE HTML>
<html>
<head>
<title>Backbone Tutorials</title>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js”></script&gt;
<script src=”underscore.js” type=”text/javascript”></script>
<script src=”backbone.js” type=”text/javascript”></script>
</head>
<body>
<script type=”text/javascript”>

</script>

</body>

</html>