Backbone.js事件监听 #

一、on方法 #

1.1 基本用法 #

javascript
var obj = _.extend({}, Backbone.Events);

obj.on('alert', function(message) {
    console.log('Alert:', message);
});

obj.trigger('alert', 'Hello');

1.2 绑定多个事件 #

javascript
obj.on('start stop reset', function() {
    console.log('事件触发');
});

obj.trigger('start');
obj.trigger('stop');

1.3 事件映射 #

javascript
obj.on({
    'start': function() { console.log('开始'); },
    'stop': function() { console.log('停止'); },
    'reset': function() { console.log('重置'); }
});

1.4 绑定上下文 #

javascript
var context = { name: 'MyContext' };

obj.on('alert', function() {
    console.log('上下文:', this.name);
}, context);

obj.trigger('alert');

1.5 使用bind #

javascript
var handler = function() {
    console.log('上下文:', this.name);
}.bind({ name: 'MyContext' });

obj.on('alert', handler);

二、listenTo方法 #

2.1 基本用法 #

javascript
var view = _.extend({}, Backbone.Events);
var model = _.extend({}, Backbone.Events);

view.listenTo(model, 'change', function() {
    console.log('模型已变化');
});

model.trigger('change');

2.2 监听多个事件 #

javascript
view.listenTo(model, 'change destroy sync', function() {
    console.log('模型事件');
});

2.3 事件映射 #

javascript
view.listenTo(model, {
    'change': function() { console.log('变化'); },
    'destroy': function() { console.log('销毁'); }
});

2.4 listenTo优势 #

javascript
var MyView = function() {
    this.model = _.extend({}, Backbone.Events);
    
    this.listenTo(this.model, 'change', this.render);
};

MyView.prototype.destroy = function() {
    this.stopListening();
};

MyView.prototype.render = function() {
    console.log('渲染');
};

2.5 on vs listenTo #

特性 on listenTo
绑定方式 对象自身 监听其他对象
内存管理 手动解绑 自动解绑
适用场景 简单场景 视图与模型

三、事件上下文 #

3.1 默认上下文 #

javascript
var obj = _.extend({}, Backbone.Events);

obj.on('alert', function() {
    console.log(this === obj);
});

obj.trigger('alert');

3.2 指定上下文 #

javascript
var context = { name: 'Custom Context' };

obj.on('alert', function() {
    console.log(this.name);
}, context);

obj.trigger('alert');

3.3 视图中的上下文 #

javascript
var UserView = Backbone.View.extend({
    initialize: function() {
        this.model.on('change', this.render, this);
    },
    
    render: function() {
        console.log(this === view);
        return this;
    }
});

3.4 使用listenTo保持上下文 #

javascript
var UserView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
    },
    
    render: function() {
        console.log(this === view);
        return this;
    }
});

四、事件参数 #

4.1 传递参数 #

javascript
obj.on('custom', function(a, b, c) {
    console.log(a, b, c);
});

obj.trigger('custom', 1, 2, 3);

4.2 事件对象 #

javascript
obj.on('save', function(data, options) {
    console.log('数据:', data);
    console.log('选项:', options);
});

obj.trigger('save', { id: 1 }, { validate: true });

4.3 多个处理函数 #

javascript
obj.on('alert', function(msg) {
    console.log('Handler 1:', msg);
});

obj.on('alert', function(msg) {
    console.log('Handler 2:', msg);
});

obj.trigger('alert', 'Hello');

五、事件解绑 #

5.1 off方法 #

javascript
var handler = function() {
    console.log('Handler');
};

obj.on('alert', handler);
obj.off('alert', handler);

5.2 解绑所有事件 #

javascript
obj.on('alert', function() {});
obj.on('warning', function() {});

obj.off();

5.3 解绑特定事件 #

javascript
obj.on('alert', function() {});
obj.on('warning', function() {});

obj.off('alert');

5.4 解绑特定处理函数 #

javascript
var handler1 = function() { console.log('Handler 1'); };
var handler2 = function() { console.log('Handler 2'); };

obj.on('alert', handler1);
obj.on('alert', handler2);

obj.off('alert', handler1);

5.5 stopListening方法 #

javascript
view.listenTo(model, 'change', handler);

view.stopListening(model);

view.stopListening();

view.stopListening(model, 'change', handler);

六、实用示例 #

6.1 视图事件绑定 #

javascript
var UserView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
    },
    
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },
    
    remove: function() {
        this.stopListening();
        Backbone.View.prototype.remove.call(this);
    }
});

6.2 集合事件监听 #

javascript
var UserListView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.collection, 'add', this.addOne);
        this.listenTo(this.collection, 'remove', this.removeOne);
        this.listenTo(this.collection, 'reset', this.render);
    },
    
    addOne: function(user) {
        var view = new UserView({ model: user });
        this.$el.append(view.render().el);
    },
    
    removeOne: function(user) {
        this.$('[data-id="' + user.id + '"]').remove();
    },
    
    render: function() {
        this.$el.empty();
        this.collection.each(this.addOne, this);
        return this;
    }
});

6.3 多模型监听 #

javascript
var DashboardView = Backbone.View.extend({
    initialize: function(options) {
        this.user = options.user;
        this.settings = options.settings;
        
        this.listenTo(this.user, 'change', this.renderUser);
        this.listenTo(this.settings, 'change', this.renderSettings);
    },
    
    renderUser: function() {
        console.log('渲染用户信息');
    },
    
    renderSettings: function() {
        console.log('渲染设置');
    },
    
    remove: function() {
        this.stopListening();
        Backbone.View.prototype.remove.call(this);
    }
});

6.4 事件代理 #

javascript
var EventProxy = {
    proxy: function(source, events, target) {
        events.split(' ').forEach(function(event) {
            this.listenTo(source, event, function() {
                var args = [event].concat(Array.prototype.slice.call(arguments));
                target.trigger.apply(target, args);
            });
        }, this);
    }
};

var CollectionView = Backbone.View.extend({
    initialize: function() {
        _.extend(this, EventProxy);
        
        this.proxy(this.collection, 'add remove reset', this);
    }
});

七、总结 #

7.1 监听方法 #

方法 说明
on(event, callback, context) 绑定事件
listenTo(obj, event, callback) 监听其他对象
once(event, callback, context) 绑定一次性事件
listenToOnce(obj, event, callback) 一次性监听

7.2 最佳实践 #

  1. 视图中使用 listenTo 绑定模型事件
  2. remove 中调用 stopListening
  3. 注意事件处理函数的上下文
  4. 合理使用事件映射简化代码
  5. 避免内存泄漏,及时解绑事件
最后更新:2026-03-28