• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • jQuery or Backbone View Event call: 2 ways do the same thing

    Blogs20142014-11-11


    jQuery or Backbone Event call: 2 ways do the same thing

    Backbone uses jQuery’s delegate() function to provide declarative callbacks for DOM events within a view. Consider the following to events call (1 is Backbone, 1 is jQuery), they are exactly the same. However, jQuery is more Succinct while Backbone is more structured and MVC-style.

    <div class="container">
        <div id="div_backbone">
            <a href="#" class="item">click to call a Backbone click event.</a>
        </div>
        <div id="div_jquery">
            <a href="#" class="item">click to call a jQuery click event.</a>
        </div>
    </div>
    <script>
        var call_this = function(e) {
            console.log('click me at: ' + $(e.target).parent('div').prop('id'));
        }
    
        var View = Backbone.View.extend({
            el: 'div#div_backbone',
            events: {
                'click .item': 'call_this'
            }
        });
    
        $(function() {
            var view = new View();
            $('div.container').delegate('.item', 'click', call_this);
        });
    </script>

    From the source code we can clearly get the answer:

    var delegateEventSplitter = /^(S+)s*(.*)$/;
    ...
        delegateEvents: function(events) {
          if (!(events || (events = _.result(this, 'events')))) return this;
          this.undelegateEvents();
          for (var key in events) {
            var method = events[key];
            if (!_.isFunction(method)) method = this[events[key]];
            if (!method) continue;
            var match = key.match(delegateEventSplitter);
            this.delegate(match[1], match[2], _.bind(method, this));
          }
          return this;
        },