正如 nl_0 的回答所说。您正在从 ajax 调用返回承诺。您想要返回或打算返回的@
是子视图实例。nl_0 对您获取数据的方式也很正确。如果您从 ajax 调用中获取数据,而不是使用 Backbones 模型和集合数据层,那么您并没有真正使用骨干网。因此,我将投票支持他的答案,但我希望以下内容确实有助于解释这个问题。
正在发生的事情是:
class ParentView extends Backbone.View
el:"#main"
childView : new ChildView
render: =>
$(@el).empty().append(@childView.render().el)
// because of the subtle mistakes in @childView.render() below
// your childView never got anything appended to it.
// @childView.render().el is undefined
// essentially $(@el).empty().append(undefined)
// that's why nothing shows up.
class ChildView extends Backbone.View
render: =>
$.ajax
url:"get_data"
success: (data) =>
// @ is not a reference to your child view.
// the value of @ has changed context
// that means @el is undefined.
// You're selecting $(undefined) not your views element.
$(@el).empty().append("Child View done")
@ // this is not your ChildView instance
你可以做的是:
class ParentView extends Backbone.View
el:"#main"
childView : new ChildView
render: =>
// this line is actually okay if we fix @childView.
$(@el).empty().append(@childView.render().el)
class ChildView extends Backbone.View
onSuccess: (data) =>
// the double arrow binds this function to the proper context
// @ is our ChildView instance
@$el.empty().append("GET get_data is done.")
render: =>
$.ajax
url:"get_data"
success: @onSuccess
// return @ out here where it is the instance.
// This is really where "Child View done".
@
对不起,如果我犯了任何错误。我的coffeescript 技能很少使用。我想这就是你的意思。非常微妙的东西,如果我需要编辑这个答案,请告诉我。
根据您的 ajax 调用需要多长时间,您可能仍会看到轻微的延迟,因为childView.render().el
将在 ajax 调用返回并附加“GET get_data 完成”之前附加到 dom。