Search code examples
backbone.jsdata-bindingunderscore.js2-way-object-databinding

BackboneJS+UnderscoreJS how to bind el back to model


I'm am the beginner in the backbone.js + underscore.js. Sorry if here is already an answer. Maybe I just dont have the right question.

I have the simple template:

<script type="text/template" id="item-template">
 <div>
   <input id="todo_complete" type="checkbox" <%= Completed ? 'checked="checked"' : '' %>            />
    <%= Title %>
  </div>
</script>

And the next view:

define(["backbone", "underscore", "jquery"],function (Backbone, _, $) {
var todoView = Backbone.View.extend({
    tagName: 'li',
    todoTpl: _.template($('#item-template').html()),

    events: {
        'change input': 'edit',
    },

    initialize: function() {
        this.$el = $('#todo');
    },

    render: function() {
        this.$el.append(this.todoTpl(this.model.toJSON()));
        this.input = this.$('.edit');
        return this;
    },

    edit: function(val) {
        //console.log(this);
        //console.log(_(this.el));
    },
});
return todoView;
});

and the model:

define(["backbone", "underscore", "jquery"], function (Backbone, _, $) {
var Todo = Backbone.Model.extend({
    defaults: {
        Title: '',
        Completed: false
    }
});
return Todo;
});

After I run render all works just fine, but after I start to edit the data in form(for example change the state of checkbox) the model in View is not getting changed. How to change it in the right way.

I know that I can add events on every input changes in the view and change the value of every attribute of the entire model by the hands. What is the best practice in this case?

Thanks a lot for any advance!


Solution

  • The best practice is called Two-Way Binding. There are two great Backbone extensions for two-way binding:

    I'm used with stickit, it's really easy deal with it.