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

gwbalxhn  于 2022-11-10  发布在  其他
关注(0)|答案(4)|浏览(136)

我尝试从子视图触发父视图的事件,但是父视图的事件似乎没有被触发。
下面是我的代码示例:

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

zfciruhq

zfciruhq1#

问题是你用错了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");
        }
  });

希望能有所帮助!

hfyxw5xn

hfyxw5xn2#

Your listenTo usage is slightly off
The signature is object.listenTo(otherObject, event, callback) so you want something like:

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

Which tells this to listen to this.subview for the event testGo and call this.addFoo when the event is triggered

atmip9wb

atmip9wb3#

试试这个

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

签名:

object.listenTo(other, event, callback)
cgvd09ve

cgvd09ve4#

触发事件:

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

监听程序:

Backbone.Events.bind('<eventname>', callback, context);

相关问题