Search code examples
javascriptjquerybackbone.jsdata-linking

Using Backbone.js and jquery.datalink.js


Is it possible to use Backbone.js and jquery.datalink.js together to link a Backbone model to a set of fields, and if so how?

For example, given:

<div id="person">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" />
</id>

and

var m = Backbone.Model.extend({});

It seems to make sense (but not work) that one could:

$("#person").link(m);

By "not work" I mean that when I change the model, the link doesn't update the input fields. When I change the input fields, the model isn't updated.

I've been tinkering with this on jsFiddle, but to no avail. Indeed, it seems the data link plugin doesn't actually work as documented (unless I've made an error).

If datalink isn't suitable for this, I'd appreciate suggestions for alternatives.

I'd be grateful for thoughts and feedback.


Solution

  • I have not used the Datalink plugin but this may help...

    This sort of violates the principle of encapsulation but you could use the model.attributes object inside the Backbone model.

    So maybe something like this:

    $("#person").link(m.attributes);
    

    Also, when you instantiate a Backbone.Model it look like this:

    var m = new Backbone.Model();
    

    When you call Backbone.Model.extend you actually create a new constructor (like a new class), not an object instance.