Backbone - 从子视图触发父视图事件

时间:2014-08-26 17:26:13

标签: javascript backbone.js

我正试图从其子视图触发父视图事件。但似乎父视图的事件没有被触发。

以下是我的代码示例:

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

我试图从谷歌搜索找到的许多解决方案中得到提示,但似乎我在某个地方受到了打击。我找到的一些选项是:

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

4 个答案:

答案 0 :(得分:5)

问题是你使用listenTo错了。

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

所以,在你的情况下,你应该这样做:

 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");
        }
  });

希望它有所帮助!

答案 1 :(得分:2)

您的listenTo使用率略有下降

签名为object.listenTo(otherObject, event, callback),因此您需要以下内容:

this.listenTo(this.subview, "testGo", this.addFoo);

告诉this收听事件this.subview的{​​{1}},并在触发事件时致电testGo

答案 2 :(得分:1)

试试这个

this.listenTo(this.subview, "testGo",this.addFoo);

签名:

     object.listenTo(other, event, callback)

答案 3 :(得分:0)

触发事件:

Backbone.Events.trigger('<eventname>', {data1 to be passed with event},  {data2 to be passed with event}...);

听众:

Backbone.Events.bind('<eventname>', callback, context);
相关问题