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>
<inp开发者_如何转开发ut 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.
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.
The solution provided by @Sam is expected to work, but it has associated issues that you must be aware of. Backbone models are observable, ie. you can bind functions to change events in models. These events are triggered by the wrapper getter and setter functions provided by Backbone. If you bypass these getters and setters, by using model.attributes directly then the events will not be triggered when the data changes. So, this is not a problem if your data-linking association is uni-directional ie. when the javascript object gets modified then the view changes, but if you want to implemenet bi-directional data-linking you will run into problems, because when the view gets manipulated by the user, the model attributes do get modified but the corresponding setters are not used and hence rest of application code is not notified of the change. This can lead to hard to debug problems. If data binding is your chief concern, do look into KnockoutJS which has state-of-the-art data linking capabilities.
精彩评论