主干-从子视图触发父视图事件

Backbone - Trigger the parent view event from child view

本文关键字:视图 事件 主干      更新时间:2023-09-26

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

以下是我的代码示例:

<!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/如何在backbonejs和requirejs 中触发从子视图到父视图的事件

2/主干:如何在父视图中触发方法

问题是您使用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");
        }
  });

希望它能有所帮助!

您的listenTo使用率略低于

签名是object.listenTo(otherObject, event, callback),所以你想要类似的东西:

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

哪一个消息告诉this为事件testGo监听this.subview,并在触发事件时调用this.addFoo

尝试这个

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

签名:

     object.listenTo(other, event, callback)

触发事件:

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

监听器:

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