主干js bindAll/bind与jQuery
我正在尝试学习主干js,但很难理解使用下划线库提供的bindAll/bind函数和jQuery函数提供的事件绑定之间的区别。以下是Coffeescript中的一个示例:主干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.
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
...
问题:
主干网还实现了一个“on”函数,该函数更类似于jQuery的“on”,但用于主干网事件。可以阅读关于的内容。
.bind
和.bindAll
之间有一个重要区别:.bind
返回绑定函数,但.bindAll
用绑定版本替换命名函数。谢谢。我不知道主干的“开启”版本。因此,如果我们在上面的代码中用主干的“on”代替jQuery的“on”。那么这两个是等价的吗?“bind”是主干中不推荐使用的“on”形式,但主干使其具有向后兼容性。