Open In App

What is Modelbinder in Backbone.js?

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:

Methods available in Modelbinder:

Steps To Use ModelBinder:

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>




<!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>




// 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:




<!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>




$(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: 


Article Tags :