Can I bind form inputs to models in Backbone.js without manually tracking blur events?

后端 未结 6 1553
抹茶落季
抹茶落季 2021-01-29 18:32

I have a backbone.js app (www.github.com/juggy/job-board) where I want to bind my form inputs directly to my model (a la Sproutcore).

Is it possible with Backbone.js (or

6条回答
  •  独厮守ぢ
    2021-01-29 18:56

    There is an even nicer way to handle this if your model includes lots of properties in it.

    SampleView = Backbone.View.extend({
        el: "#formEl",
    
        events: {
            "change input": "changed",
            "change select": "changed"
        },
    
        initialize: function () {
            _.bindAll(this, "changed");
        },
    
        changed:function (evt) {
           var changed = evt.currentTarget;
           var value = $(evt.currentTarget).val();
           var obj = {};
           obj[changed.id] = value;
           this.model.set(obj);
        }
     });
    

    There is a reliance on your input elements having an id the same as the what the name of the property in your model is.

提交回复
热议问题