1

可能重复:
Backbone.js 中不同视图的调用方法

我是主干.js 的新手,我正在使用带有 ASP.NET MVC 4 的主干.js。

我有一个名为 SomeObject 的全局类,其中有一个 deleteUser 函数。此函数与 MyView2 中存在的按钮的单击事件之一绑定。

如何从此全局函数/类中调用不同视图中存在的以下主干.js 不同函数。

  • 调用 MyView 2 的 myMethodB
  • 调用 MyView 1 的 myMethodA
  • 调用 AppView 的 myMethodC

请指导我。我仍在学习backbone.js,可能做错了什么。谢谢

var SomeObject = function (Id, Name) {
    var self = this;
    this.Id = Id;
    this.Name = Name;
    this.deleteUser = function () {
        console.log(self.Id, self.Name);

        // call myMethodB of MyView 2
        // call myMethodA of MyView 1
        // call myMethodC of AppView
    };
};

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

var AppView = Backbone.View.extend({
...
myMethodC: function(){
 // do something with App View 
}
...
});
4

1 回答 1

1

您应该使用 Backbone 事件 - http://backbonejs.org/#Events

var SomeObject = function (Id, Name) {
    var self = this;
    this.Id = Id;
    this.Name = Name;
    this.deleteUser = function () {
        console.log(self.Id, self.Name);

        viewInstances.MyView2.trigger('eventFormyMethodB')
        viewInstances.MyView1.trigger('eventFormyMethodA')
        viewInstances.AppView.trigger('eventFormyMethodC')
    };
};

var viewInstances = {
    MyView2: new MyView2({...}),
    MyView1: new MyView1({...}),
    AppView: new AppView({...})
}

例如

var AppView = Backbone.View.extend({
...
    events: {
        'eventFormyMethodC': 'myMethodC'
    },
    myMethodC: function(){
    // do something with App View 
    }
...
});
于 2012-10-05T10:09:55.507 回答