Backbone.js 中不同视图的调用方法 [英] Call methods of different views in Backbone.js
问题描述
我在 ASP.NET MVC 4 中使用了 Backbone.js.
I am using backbone.js with ASP.NET MVC 4.
我想从一个视图中调用不同视图的方法.为了让这个更容易理解,我在下面创建了一个小例子.
I want to call methods of different view from one of the view. To make this simpler to understand I have created a small example below.
这里在 MyView2 旁边的 OperationCompleted 方法中我想调用以下...
Here in the MyView2 in side the OperationCompleted method I want to call the following...
- 调用 MyView 2 的 myMethodB
- 调用 MyView 1 的 myMethodA
- 调用 AppView 的 myMethodC
我该怎么做?我暂时使用了诸如创建视图对象并调用它们之类的方法.
How do I do this ? I have temporarily used something like creating objects of view and calling them.
像这样var view1 = new MyView1();
然后view1.myMethodA();
,一定有更好的方法,请帮我找到它.谢谢
Something like this var view1 = new MyView1();
and then view1.myMethodA();
, there has to be a better way, Please help me find it. Thanks
var MyModel = Backbone.Model.extends({
});
// View for a Main Grid
var MyView1 = Backbone.View.extend({
...
myMethodA: function(){
// do something with View 1
}
...
});
// View for subgrid in Main Grid
var MyView2 = Backbone.View.extend({
...
myMethodB: function(){
// do something with View 2
},
OperationCompleted: function(){
// call myMethodB of MyView 2
// call myMethodA of MyView 1
// call myMethodC of AppView
}
...
});
var AppView = Backbone.View.extend({
...
myMethodC: function(){
// do something with App View
}
...
});
推荐答案
成功了!不得不使用聚合器模式,在下面粘贴了我如何使用它的示例示例...
Got this working ! had to use the Aggregator pattern, have pasted below a sample example of how I used it...
Backbone.View.prototype.eventAggregator = _.extend({}, Backbone.Events);
var model = Backbone.Model.extend({
});
var view1 = Backbone.View.extend({
initialize: function () {
this.eventAggregator.bind("doSomething_event", this.doSomething);
},
doSomething: function(name){
alert("Hey " + name + " !");
}
});
var view2 = Backbone.View.extend({
callToDoSomething: function(){
self.eventAggregator.trigger("doSomething_event", "Yasser");
}
});
参考资料
https://stackoverflow.com/a/11926812/1182982
这篇关于Backbone.js 中不同视图的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!