Backbone js带有变量的动态事件

onl*_*oon 2 javascript backbone.js

让我们说我有这个观点:

var HomeView = Backbone.View.extend({
    el: '#application',
    initialize: function() {
        this.template = template; // Comes from requireJS (not relevant)
        this.$elements = {};
    },
    render: function() {
        this.$el.html(this.template);

        this.$elements = {
            signIn: {
                email: $('#sign-in-email'),
                password: $('#sign-in-password')
            }
        };

        // Demonstration.
        this.$elements.signIn.email.myPluginInit();
        this.$elements.signIn.password.myPluginInit();

        //
        // NOTE: How to handle the events?
        //
    }
});
Run Code Online (Sandbox Code Playgroud)

我有这个.$ elements对象,它将包含我DOM中的所有对象,如何将事件放在它们上面因为这个解决方案它们是可变的.这就是我以前做的事情(参见backbone.org).

var HomeView = Backbone.View.extend({
  events: {
    'click #sign-in-email': 'clickedSignInEmail',
    'focus #sign-in-password': 'focusSignInPassword'
  }
});
Run Code Online (Sandbox Code Playgroud)

Mis*_*lin 8

与在渲染期间手动使用jQuery将事件绑定到子元素相比,使用delegateEvents提供了许多优势.在传递给jQuery之前,所有附加的回调都绑定到视图,因此在调用回调时,这将继续引用视图对象.当再次运行delegateEvents时,可能使用不同的事件哈希,所有回调都将被删除并重新委派 - 对于在不同模式下需要表现不同的视图非常有用.

示例代码:

initialiaze: function () {
  // …
  this.events = this.events || {};
  // dynamically build event key
  var eventKey = 'click ' + '#sign-in-email';
  this.events[eventKey] = 'clickedSignInEmail';
  this.delegateEvents();
  // …
}
Run Code Online (Sandbox Code Playgroud)