【问题标题】:Backbone + JQuery Plugin won't work (Written in CoffeeScript)Backbone + JQuery 插件不起作用(用 CoffeeScript 编写)
【发布时间】:2012-08-21 15:26:34
【问题描述】:

好的,我有一个简单的 JQuery 插件,当应用于 div 时,它将使用预加载器图像整齐地加载该 div 中的所有图像。这很好用。

但是,在 Backbone 中,我在页面加载后将数据从 JSON 附加到元素。因此下面的代码将不起作用。

$(document).ready( ->
    $("#theList").preloader()
)

所以我需要在生成列表后将“$("#theList").preloader()”放入我的渲染函数中..

class HomeView extends Backbone.View
constructor: ->
    super

initialize: ->
    @isLoading = false

events: {
     "click #nextPage": "nextPage"
     "click #prevPage": "prevPage"  
}


template: _.template($('#home').html())
theListTemplate: _.template($('#theList').html())

render: ->
    $(@el).append(@template)
    @loadResults()
    $("#theList").preloader() #<----------------- DOESN'T WORK NOW


loadResults: () ->
    @isLoading = true

    Properties.fetch({
        success: (data) =>

            #Append properties to list
            $('#theList').append(@theListTemplate({data: data.models, _:_})).listview('refresh')


        error: ->
            @isLoading = false
            alert('Unable to load information')
    })

但是,现在代码行在主干视图/模型/控制器或其他任何内容中,它不起作用..

作为参考,我像这样加载我的应用程序..

$(document).ready( ->
    console.log('document ready')
    app.AppRouter = new AppRouter()
    Backbone.history.start()
)

任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: jquery jquery-mobile backbone.js coffeescript


    【解决方案1】:

    假设预加载器不打算在loadResults#fetch#success 中添加的节点上运行(因为在您调用预加载器时 fetch 尚未返回),我怀疑问题在于,在执行 @ 987654323@ 函数,视图的el 还不是 DOM 的一部分。

    如果你调用HomeView 喜欢

    myHomeView = new HomeView()
    $('some selector').append(myHomeView.render().el)
    

    HomeView 的 el 尚未添加到 DOM,它在一个分离的文档中。

    因此 jQuery 选择器 $("#theList") 返回一个空结果 - 因为它正在搜索 DOM。这可以通过 console.log'n 选择器的结果轻松验证,或者使用调试器设置断点并使用控制台进行测试。

    谢天谢地,修复很简单。您需要通过使用jQuery reference scoped to the view 将选择器范围限定为视图来引用分离的文档:

    @$("#theList").preloader()
    

    或者,自己做

    $(@el).find("#theList").preloader()
    

    【讨论】:

    • 哇!是的。固定的。感谢您发现这一点。
    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    相关资源
    最近更新 更多