Open In App

What is Modelbinder in Backbone.js?

Last Updated : 07 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The ModelBinder in Backbone.js is a popular plugin that provides two-way data binding between Backbone models and HTML elements. Modelbinder is not a built-in feature of the framework.

To use the modelBinder plugin, you need to include the plugin file in your project and ensure it is loaded after Backbone.js itself. You can find the plugin code and documentation on GitHub.

Syntax: 

const modelBinder = new Backbone.ModelBinder();
modelBinder.bind(model, rootEl, bindings, options);
modelBinder.unbind();

 

Parameters:

  • model – The backbone model that you want to bind.
  • rootEl – The root HTML element that contains the elements you want to bind to.
  • bindings – An object that maps HTML element IDs to model attributes.
  • options – An object that contains additional options, such as whether or not to bind read-only elements.

Methods available in Modelbinder:

  • unbind() Method – Unbinds the model from the specified HTML elements.
  • bind() Method – Binds the model to the specified HTML elements.

Steps To Use ModelBinder:

  • Step 1: Download the ModelBinder plugin and include it in your project: You can use a package manager like npm or Yarn to install the library.
  • Step 2: Define your Backbone model and Create an instance of the Model. Create a Backbone model by extending Backbone.Model.
  • Step 3: Define your Backbone view and use the ModelBinder. Create a Backbone View by extending Backbone. View
    Use the ModelBinder to bind the model and the view.
  • Step 4: Instantiate your Backbone view. Create a new instance of your view and pass the model and the 
    target container element as options.

Example 1: Include the Necessary CDN Links: Include Backbone.js, Underscore.js, and the ModelBinder library in your HTML file:

<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.1/backbone-min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/backbone.modelbinder/1.1.0/Backbone.ModelBinder.min.js”></script>

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="UTF-8">
    <title>Backbone Model Binder Example</title>
    <script src=
    </script>
    <script src=
    </script>
    <script src="
</script>
    <script src=
    </script>
</head>
  
<body style="background-color: aliceblue;">
    <form id="myForm">
        <label for="name">Enter the Name:</label>
        <input type="text" id="name" name="name">
        <br>
        <label for="desc">Enter the Description:</label>
        <input type="text" id="desc" name="desc">
        <br>
        <button type="submit">Save</button>
    </form>
    <script src="app.js"></script>
</body>
  
</html>


Javascript




// Define the model
let DemoModel = Backbone.Model.extend({
    defaults: {
        name: 'xyz',
        desc: ''
    }
});
  
// Define the view
let DemoView = Backbone.View.extend({
    el: '#myForm',
  
    events: {
        'submit': 'saveUser'
    },
  
    initialize: function () {
        this.modelBinder = new Backbone.ModelBinder();
        this.render();
    },
  
    render: function () {
        this.modelBinder.bind(this.model, this.el);
        return this;
    },
  
    saveUser: function (e) {
        e.preventDefault();
        this.modelBinder.unbind();
        console.log(this.model.toJSON());
    }
});
  
// Create an instance of the model
let demo = new DemoModel();
  
// Create an instance of the view
let demoView = new DemoView({ model: demo });


Output: For example, if you entered “GeeksForGeeks” in the Name field and “Best Coding Website For Coders” in the Description field, the output would be:

 

Example 2:

HTML




<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ModelBinder Example</title>
    <script src=
      </script>
    <script src=
      </script>
    <script src=
      </script>
    <script src=
      </script>
  
    <script src="app.js"></script>
</head>
  
<body>
    <h1>ModelBinder Example</h1>
    <form id="myForm">
        <input type="text" id="nameInput" 
               name="name"
               placeholder="Enter your name">
        <input type="text" id="ageInput" 
               name="age" 
               placeholder="Enter your age">
        <button type="submit">Submit</button>
    </form>
    <div id="output"></div>
</body>
</html>


Javascript




$(document).ready(function () {
    // Define the model
    let UserModel = Backbone.Model.extend({
        defaults: {
            name: '',
            age: 0
        }
    });
  
    // Define the view
    let UserView = Backbone.View.extend({
        el: '#myForm',
        events: {
            'submit': 'submitForm'
        },
        initialize: function () {
            this.modelBinder = new Backbone.ModelBinder();
        },
        render: function () {
            let bindings = {
                name: '#nameInput',
                age: '#ageInput'
            };
            this.modelBinder.bind(this.model, this.el, bindings);
            return this;
        },
        submitForm: function (e) {
            e.preventDefault();
            this.model.set('name', this.model.get('name').trim());
            this.model.set('age', parseInt(this.model.get('age')));
  
            // Display the model values in the output div
            $('#output').html('<strong>Name:</strong> '
                this.model.get('name') + 
                '<br><strong>Age:</strong> '
                this.model.get('age'));
        }
    });
  
    let userModel = new UserModel();
    let userView = new UserView({ model: userModel });
    userView.render();
});


Output: This example demonstrates a simple form with two inputs (name and age). The ModelBinder is used to bind the input values to the model attributes, and when the form is submitted, the model values are displayed in the output div.

 

Conclusion: 

  • In conclusion, ModelBinder is a useful library in the Backbone.js framework that simplifies the process of data binding between models and views. It provides an easy-to-use syntax for defining bindings and automatically synchronizes the model and view data. 
  • By using ModelBinder, developers can reduce boilerplate code, improve code readability, and focus on business logic and UI design. It’s a powerful tool that streamlines the development process, and it’s worth considering for any Backbone.js project that requires data binding between models and views.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads