Call methods of different views in Backbone.js

2020-03-30 01:47发布

问题:

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.

Here in the MyView2 in side the OperationCompleted method I want to call the following...

  • call myMethodB of MyView 2
  • call myMethodA of MyView 1
  • call myMethodC of AppView

How do I do this ? I have temporarily used something like creating objects of view and calling them.

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

回答1:

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

References

https://stackoverflow.com/a/11926812/1182982



回答2:

Another pattern here would be to call a view's function by triggering an event on the DOM element the view is attached to.

For example:

var AppView = Backbone.View.extend({
  el: 'body',
  events: {
    'alertMe': 'alertMe'
  },
  alertMe: function(ev, arg){
    console.log(args)
    alert("You've been alerted!")
  }
});

Then at some point later in your code (even in another view):

// Shows an alert and prints object.
$('body').trigger('alertMe', { foo: 'bar' });