主干js bindAll/bind与jQuery

主干js bindAll/bind与jQuery,jquery,binding,backbone.js,Jquery,Binding,Backbone.js,我正在尝试学习主干js,但很难理解使用下划线库提供的bindAll/bind函数和jQuery函数提供的事件绑定之间的区别。以下是Coffeescript中的一个示例: class Raffler.Views.Entry extends Backbone.View template: JST['entries/entry'] tagName: 'li' events: 'click': 'showEntry' initialize: -> @model.

我正在尝试学习主干js,但很难理解使用下划线库提供的bindAll/bind函数和jQuery函数提供的事件绑定之间的区别。以下是Coffeescript中的一个示例:

class Raffler.Views.Entry extends Backbone.View
  template: JST['entries/entry']
  tagName: 'li'

  events:
    'click': 'showEntry'

  initialize: ->
    @model.on('change',@render,this)
    @model.on('highlight',@highlightWinner,this)

  showEntry: ->
    Backbone.history.navigate("entries/#{@model.get('id')}", true)

  highlightWinner: ->
    $('.winner').removeClass('highlight')
    @$('.winner').addClass('highlight')

  render: ->
    $(@el).html(@template(entry: @model))
    this

This is a snippet of code from Ryan Bate's RailsCasts' on Backbone.js

Seems to me that the same code can be written using the underscore bindAll and bind functions as follows:

class Raffler....
  ...
  initialize: ->
    _bindAll @, 'render', 'highlightWinner'
    @model.bind 'change',@render
    @model.bind 'highlight',@highlightWinner
  ...
问题:

  • 这两者在功能上是等价的吗
  • 如果是,那么jQuery代码看起来更清晰、更明确。这只是个人喜好的问题吗
  • 提前感谢您抽出时间

    Bharat

    jQuery的“on”用于与主干网的“bind/bindAll”完全不同的用途。jQuery的“on”的目的是在事件发生时调用函数。下划线的bind或bindAll用于将函数绑定到对象,这意味着无论何时调用函数,该函数的值都将是调用bind时传递的对象。下划线的bindAll与bind的作用完全相同,只是同时使用多个函数

    您会发现,在使用主干构建时,这些将一起使用。假设您使用内部调用的函数设置了一个模型,以修改模型。如果使用jQuery或主干的“on”函数将该函数绑定到事件,当它触发事件时,这将是触发事件的DOM元素,这意味着该函数中对它的任何引用都将不再有效,因为它不再是一个模型,而是一个DOM元素。但是,如果我们要在模型的构造函数中调用u.bind(这个,回调),它将确保这始终是模型


    主干网还实现了一个“on”函数,该函数更类似于jQuery的“on”,但用于主干网事件。可以阅读关于

    的内容。
    .bind
    .bindAll
    之间有一个重要区别:
    .bind
    返回绑定函数,但
    .bindAll
    用绑定版本替换命名函数。谢谢。我不知道主干的“开启”版本。因此,如果我们在上面的代码中用主干的“on”代替jQuery的“on”。那么这两个是等价的吗?“bind”是主干中不推荐使用的“on”形式,但主干使其具有向后兼容性。