6

我想知道是否可以使用 BackboneJS 从子视图调用视图函数。如果是,它是如何工作的?

我想从子视图中调用属于 mainView 的函数“hello”。

也许如果事件触发......

例子:

var MainView = Backbone.View.extend({

    initialize: function() {
        this.$template = $(template);
        this.subview = new SubView();               
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        var element = this.$template.attr('id');
        this.subview.setElement('#'+element).render();
    },

    hello: function() {
        alert('Hello');
    }

});


var SubView = Backbone.View.extend({

    initialize: function() {
        this.$template = $(template);           
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        //Call view function ' hello '
        //parentView.hello();
    }

});

谢谢!

4

2 回答 2

8

您可以将父视图中的引用传递给子视图:

http://jsfiddle.net/puleos/hecNz/

var MainView = Backbone.View.extend({

    initialize: function() {
        this.$template = $("<span>foo</span>");
        this.subview = new SubView({parent: this});               
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        var element = this.$template.attr('id');
        this.subview.setElement('#'+element).render();
    },

    hello: function() {
        alert('Hello');
    }

});


var SubView = Backbone.View.extend({

    initialize: function(options) {
        this.$template = $("<span>bar</span>");
        this.parent = options.parent;
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        this.parent.hello();
    }

});

var mainView = new MainView();

console.log(mainView);
于 2013-05-07T20:14:35.160 回答
2

您可以尝试MainView像这样扩展:

var SubView = MainView.extend({ });

那应该给你一个对hello.MainView

或者,在 中SubView,将其添加到您的render函数中:

MainView.prototype.hello.call(this) 

这将在使用实例的上下文(模板、其他变量等)时调用该hello函数。MainViewSubView

于 2013-05-08T03:15:21.597 回答