我尝试从子视图触发父视图的事件,但是父视图的事件似乎没有被触发。
下面是我的代码示例:
<!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条答案
按热度按时间zfciruhq1#
问题是你用错了listenTo。
因此,在您的情况下,您应该这样做:
希望能有所帮助!
hfyxw5xn2#
Your
listenTo
usage is slightly offThe signature is
object.listenTo(otherObject, event, callback)
so you want something like:Which tells
this
to listen tothis.subview
for the eventtestGo
and callthis.addFoo
when the event is triggeredatmip9wb3#
试试这个
签名:
cgvd09ve4#
触发事件:
监听程序: