编辑:如果您有 data-foreach 来生成选项,这可能会变得更加复杂。我在这个答案的末尾添加了一个更强大的Select2View!
我猜 document.ready 在 Batman 视图实际呈现之前被触发,因此 DOM 尚未填充。 jQuery 调用不匹配任何元素,因为它们还没有出现在页面上。
尝试定义一个自定义视图,挂钩到它的生命周期,然后在 HTML 中绑定到该视图。
自定义视图:
class MyApp.Select2View extends Batman.View
viewDidAppear: ->
$("#e1").select2();
在您的 HTML 中:
<div data-view='Select2View'>
<select id='e1' data-bind='item.value'>
<!-- your options here! -->
</select>
</div>
在此处了解有关查看生命周期回调的更多信息:http://batmanjs.org/docs/views.html#view-lifecycle
其他 Select2View:
(也在pastebin上)
# Use select2 with a batman.js view binding
#
# Usage:
# <select data-view='Select2View' data-view-bind='myRecord.myProperty'>
# <option data-foreach-opt='myOptions' data-bind='opt.name' data-bind-value='opt.id'>
# </select>
#
# Note that the property name is passed in as `data-view-bind`. This goes with `@option 'bind'` in the View definition.
class App.Select2View extends Batman.View
@option 'bind', 'placeholder'
constructor: ->
super
@on 'childBindingAdded', @childBindingAdded
_addChildBinding: (binding) ->
super
@fire('childBindingAdded', binding)
ready: ->
unless @select2
options = { minimumResultsForSearch: 12 }
options.minimumResultsForSearch = -1 if $(@node).hasClass("select2--nosearch")
if placeholder = @get('placeholder')
options.placeholder = placeholder
@select2 = $(@node).select2(options)
@select2.on 'change', @select2Changed
@dataChanged()
select2Changed: =>
value = @select2.select2("val")
# coercion to integer borrowed from old Batman.js code https://github.com/batmanjs/batman/commit/b9c208a5f232fd505d58ac13dbdcb0ad00887457
if (typeof value is "string") and value.match(/[^0-9]/) is null and "#{coercedValue = parseInt(value, 10)}" is value
value = coercedValue
@set 'bind', value
childBindingAdded: (binding) =>
if binding instanceof Batman.DOM.IteratorBinding
binding.backingView.on 'itemsWereRendered', => @dataChanged()
@dataChanged()
dataChanged: ->
if @select2 and (typeof @bind isnt 'undefined')
@select2.select2("val", @bind)
@accessor 'bind',
get: ->
@bind
set: (name, value) ->
@bind = value
@dataChanged()