backbone

backbone practice

by Mehmetcan Sinir

HTML

<script src="https://rawgit.com/douglascrockford/JSON-js/master/json2.js"></script>
<script src="https://rawgit.com/jashkenas/backbone/1.0.0/backbone-min.js"></script>
<script src="https://rawgit.com/jeromegn/Backbone.localStorage/v1.1.6/backbone.localStorage.js"></script>
<script src="http://www.fsfoo.com/js/vendor/handlebars-1.0.rc.2.js"></script>
<body>
    <div id="todo">
    </div>
    <script type="text/x-handlebar-template" id="item-template">
        <div>
            <input id="todo_complete" type="checkbox" {{#if completed}} "checked" {{/if}}/>
                <label>{{title}}</label>
        </div>
        </script>
</body>

JavaScript

//LOOKING AT MODELS A BIT CLOSER
// Enter the example code here

var Person = new Backbone.Model();
console.log(Person.name);
Person.on("change:name", function() {console.log("the name has been changed")});
Person.set({name: "Mehmetcan"});
console.log("attributes are", Person.attributes.name);
console.log(Person.hasChanged("name"));


//it is good to listen for changes in the initialize function, which is called when the model is initialized.

//model change listeners
var Todo = Backbone.Model.extend({
    defaults: {
        title: '',
        completed: false
    },
    
    initialize: function(){
        console.log("a new model has been initialized");
        this.on("change:title", function(){
            console.log("the title has been changed");
        });
    },
    
    setTitle: function(newTitle) {
        this.set({title: newTitle});
    },
});

var todo = new Todo();


//if you set values through the attributes attribute, you can bypass the event listeners
todo.set('attritutes.title', "joe");

//if you don't use the attributes, it will trigger the listener
todo.set({title: "mehmetcan"});

//model instances attributes are gotten by the get method
console.log(todo.get('title'));








//DEFINE A TODO MODEL AND CREATE A TODO INSTANCE
//you extend the backbone model to have the following attributes and build a Todo constructor
var Todo = Backbone.Model.extend({
    defaults: {
        title: '',
        completed: false
    }
});
//in backbone you can change the attribute of a model instance while creating it.
var myTodo = new Todo({title: 'Check attributes property of the logged module in the console'});

//DEFINE VIEWS WHICH HAS HANDLER AND CONTROLLING LOGIC
var TodoView = Backbone.View.extend({
    tagname: 'li', //this creates a 'li' element which is referenced by the 'el' property
    
    todoTpl: Handlebars.compile($('#item-template').html()),
    
    //this is the event handling logic. The Backbone events hash allows us to attach event...