An example of data binding to the DOM

I read the following in Backbone.js ':

When working on a web application that has a lot of JavaScript involved, one of the first things you learn is to stop linking your data to the DOM. It's too easy to create JavaScript applications that end up like tangled piles of jQuery selectors and callbacks, all attempts to frantically keep data in sync between the HTML UI, your JavaScript logic and the database on your server. For a wealthy client side, a more structured approach is often useful.

I'm not sure if I understand the above passage (I'm not sure if I understand the need to use Backbone.js).

Can someone give me an example of data binding with DOM and how does Backbone.js solve it?

EDIT:

This is an example?

jQuery(document).ready(function($) { // Header jQuery('#header #searchbox').attr('placeholder', '<?php echo pll__("Header Search Field"); ?>'); (etc...) 

(I used to hack it, since I did not know how to do it with php).

So, if I change the identifier of #searchbox or move its position, the code will not work again. Is this what is said above?

+6
source share
1 answer

I just did something using a trunk that displays an edit text box where you can edit the project name. Since this name is also displayed on the main page, I want to update it at the same time. But I do not want to identify the DOM element and update it directly using my editing. Instead, I create a base model:

 this.newModel = new app.Project({model: this.model}); 

Then I listen to the new model for any changes, in this case for the project_name attribute:

 this.listenTo(this.newModel, 'change:project_name', this.updateName); 

Then I create a new view using 'newModel'

 modal = new app.ProjectModal({ model: this.newModel, }); 

This is then displayed, and if the name changes in the modal view, the "this.updateName" function is run in the "parent" view, which eliminates the need to identify where the actual DOM element is.

The entire "parent" function looks like this:

  app.ProjectCardView = Backbone.View.extend({ tagName: 'article', className: 'project', template: _.template( $("#tpl-project-card-summary").html() ), events: { 'click .settings-btn': 'showProjectModal' }, initialize: function() { //a slightly different model is used to populate project than this card... this.newModel = new app.Project({model: this.model}); return this; }, render: function() { this.$el.html( this.template(this.model.toJSON()) ); return this; }, showProjectModal: function (e) { this.listenTo(this.newModel, 'change:project_name', this.updateName); this.modal = new app.ProjectModal({ model: this.newModel }); return this; }, updateName: function() { if (this.modal) { this.$el.find('.item_name').text(this.model.get("project_name")); } return this; } }); 

Obviously, I need to update the DOM somewhere, but now it is separate from editing and easier to manage.

+1
source

All Articles