Search code examples
javascriptbackbone.js

How to pass data to a View in Backbone.js?


I am trying to pass data to SingleTodo view in Backbone.js. But, it is not passing properly.
For more clarity, please see the code and outputs given below.

Code:
temp.html

<h1>This is Temp</h1>

<div id="app"></div>

<script type="text/template" id="app-template">
  Title: <%= title %><br/>
  isCompleted: <%= isCompleted %>
</script>

temp.js

const SingleTodo = Backbone.Model.extend({
  defaults: {
    title: "",
    isCompleted: false
  }
});

const TodoView = Backbone.View.extend({
  el: "#app",
  template: _.template($("#app-template").html()),

  initialize: function () {
    this.model = new SingleTodo();
    this.render();
  },

  render: function () {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

$(document).ready(function () {
  const todoView = new TodoView();

  todoView.model.set({
    title: "A simple to-do",
    isCompleted: true
  });
});

Output:
Expected
Expected

Getting
Getting

What is wrong in my code because of which I am not getting expected output?


Solution

  • You are missing the following line in the initialize method of TodoView:

    this.listenTo(this.model, 'change', this.render);
    

    Aside: instead of setting this.model inside the view's initialize method, I recommend passing it from the outside. In your example, change the first line of the $(document).ready handler:

    const todoView = new TodoView({model: new SingleTodo()});