Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

I Up-voted Juliano's answer. There's a lot out there on two way binding and I also use stickit. Having said that it doesn't always make things easier than just manually re-rendering a partial template when a model is changed.

Think about it carefully, how do you want your models to be updated? Do you want every change to be immediately thrown into your model - or do you just want to update the template once changes have been committed.

Derek Bailey wrote a good article on his solution to this problem: http://lostechies.com/derickbailey/2011/07/24/awesome-model-binding-for-backbone-js/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top