我有一个名为select2的插件,我通常在我的javascript文件中调用插件,如下所示: $(document).ready(function(){$(“#e1”)。select2();});
但在我的蝙蝠侠应用程序上,我不知道我应该把它放在哪里。我可以将它放在libs文件夹(my_helper.js)中,但是它不起作用,是否还有另一个传统上这个jquery调用应该去的地方?
感谢。
答案 0 :(得分:0)
编辑:如果您有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()