Search code examples
javascriptbackbone.js

Backbone - Trigger the parent view event from child view


I am trying to trigger the event of parent view from its child view. But it seems that the parent view's event did not gets triggered.

Following is the sample for my code:

<!DOCTYPE html>
<html>

<head>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

    <script>

    MySubView = Backbone.View.extend({
        id : "MySubView",

        initialize: function() {
          console.log("pro1");

          this.trigger("testGo", "test");
        }
    });

    MyView = Backbone.View.extend({
        id : "MyView",

        initialize: function() {
          console.log("pro");
          this.subview = new MySubView();
          this.subview.listenTo("testGo", this.addFoo, this);
        },

        addFoo: function() {
          console.log("ok");
          alert("ok");
        }
  });

  new MyView();

</script>

</head>

<body>
</body>
</html>

I tried to get hint from many solutions found via google search, but it seems I am got struck somewhere. Some of the options which I found are :

1/ How to trigger an event from child view to parent view in backbonejs and requirejs

2/ Backbone: How to trigger methods in a parent view


Solution

  • The problem is that you are using listenTo wrong.

    anObject.listenTo(anotherObject, 'forSomeEvent', function () { console.log('do something'); });
    

    So, in your case, you should do it like this:

     MyView = Backbone.View.extend({
            id : "MyView",
    
            initialize: function() {
              console.log("pro");
              this.subview = new MySubView();
              this.listenTo(this.subview, 'testGo', this.addFoo);
            },
    
            addFoo: function() {
              console.log("ok");
              alert("ok");
            }
      });
    

    Hope it helps!