单击子视图时,Backbone.js执行函数

时间:2015-02-16 15:36:29

标签: javascript jquery backbone.js

我有一个名为DatesView的视图和一个名为DateView的子视图。我想在单击DateView实例时在DatesView中执行一个函数。

var Date = Backbone.Model.extend({});

var Dates = Backbone.Collection.extend({
    model: Date
});

var DateView = Backbone.View.extend({
    events: {
        'click': 'clicked'
    },

    render: function () {
        this.$el.text(this.model.get('date'));

        return this;
    }
})

var DatesView = Backbone.View.extend({
    render: function () {
        this.collection.each(function (date) {
            var dateView = new DateView({model: date});

            this.$el.append(dateView.render().el)
        }, this);

        return this;
    },

    clicked: function() {
        console.log('clicked');
    }
})

var dates = new Dates([
    {date: '01'},
    {date: '02'},
    {date: '03'}
])

var datesView = new DatesView({collection: dates});

$('#container').html(datesView.render().el);

JSFiddle

正如您在示例中所看到的,DateView具有click的事件设置,我想在DatesView中注册。它现在写的方式不起作用。

2 个答案:

答案 0 :(得分:1)

最简单的方法是接受"点击"子视图中的选项:

var DateView = Backbone.View.extend({
    events: {
        'click': 'clicked'
    },
    initialize: function (options) {
        // allow parent to pass in a click handler
        this.clicked = options.clicked;
    }
    // snip...
})

var DatesView = Backbone.View.extend({
    render: function () {
        this.collection.each(function (date) {
            // pass parentView's click method to child, 
            // binding context to parent
            var dateView = new DateView({
                  model: date, 
                  clicked: this.clicked.bind(this)
            });

            this.$el.append(dateView.render().el)
        }, this);

        return this;
    },
    // snip...

jsfiddle

答案 1 :(得分:1)

我非常喜欢使用Backbone事件。您可以按如下方式使用它:

在DateView中触发事件

clicked: function () {
    Backbone.trigger('date:clicked');
}

在DatesView中收听事件

initialize: function () {
    this.listenTo(Backbone, 'date:clicked', this.clicked);    
}