Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 other tools) without actually tracking each blur events on the inputs and updating the model manually? This seems like a lot of glue code.

Thanks,
Julien

like image 843
Julien Avatar asked Nov 02 '10 03:11

Julien


2 Answers

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.

like image 196
Malcolm Sharman Avatar answered Sep 18 '22 13:09

Malcolm Sharman


I'm not sure how SC does it but probably they listen for events too.

window.SomeView = Backbone.View.extend({   events: {     "change input.content":  "contentChanged"   },   initialize: function() {     _.bindAll(this, 'contentChanged');     this.inputContent = this.$('input.content');   },   contentChanged: function(e) {     var input = this.inputContent;      // if you use local storage save      this.model.save({content: input.val()});      // if you send request to server is prob. good idea to set the var and save at the end, in a blur event or in some sync. maintenance timer.     // this.model.set({content: input.val()});   } }); 
like image 40
clyfe Avatar answered Sep 18 '22 13:09

clyfe