【问题标题】:Backbonejs having trouble with a get request inside of my viewBackbonejs 在我的视图中遇到获取请求的问题
【发布时间】:2016-12-11 03:57:28
【问题描述】:

我正在尝试在我的backbonejs 视图渲染方法中发出获取请求。在 ajax 调用成功后,我想渲染我的模板。我在访问最初传递到视图中的模型时遇到问题。我只能访问来自 ajax 请求的数据。如何在成功调用 ajax 时让我的 @user 模型可用?

FooAdmin.Views.Users ||= {}

class FooAdmin.Views.Users.ShowView extends Backbone.View    
  initialize: ->
    @user = @model

  template: HandlebarsTemplates["users/show"]

  render: ->   
    @self = @$el.html
    $.ajax FooAdmin.FOO_API_URL + "/api/v1/orders?user_id=#{@user.attributes.id}",
      type: 'GET'
      dataType: 'json'

      error: (jqXHR, textStatus, errorThrown) ->
        alert(textStatus)
      success: (data, textStatus, jqXHR) ->
        debugger;
        @self.html(@template(user: @user, order: data))

【问题讨论】:

  • 您可能必须将成功调用绑定到父对象。绕过 Backbone 并使用 jQuery 不会保留上下文。我通常将 _.bind 用于此类事情。
  • 看起来当我检查放置debugger的父级时,父级是窗口。
  • @self = @$el.html 没有多大意义,在@self@ 中留下函数引用不一定是您希望它在success 回调中的样子.你不想在回调中更喜欢el = @$el 然后el.html(...) 吗?此外,FooAdmin.FOO_API_URL + "/api/v1/orders?user_id=#{@user.attributes.id}" 可能只是 "#{FooAdmin.FOO_API_URL}/api/v1/orders?user_id=#{@user.attributes.id}",看起来更一致。
  • 在 ajax 调用之前我可以做这样的事情来访问用户对象吗? user = @user那直接不行,不过说不定有类似的功能。

标签: jquery ajax backbone.js coffeescript


【解决方案1】:

success 函数中的 @ 引用的作用域导致了问题。此时 @ 不再像您期望的那样引用您的班级。通常情况下,我会在内部函数中添加对类或对象的显式引用。请参阅下面的第一行 render,以及在 success 中将 @ 替换为 thisRef 的更改。 p>

FooAdmin.Views.Users ||= {}

class FooAdmin.Views.Users.ShowView extends Backbone.View    
  initialize: ->
    @user = @model

  template: HandlebarsTemplates["users/show"]

  render: ->   
    thisRef = @
    @self = @$el
    $.ajax FooAdmin.FOO_API_URL + "/api/v1/orders?user_id=#{@user.attributes.id}",
      type: 'GET'
      dataType: 'json'

      error: (jqXHR, textStatus, errorThrown) ->
        alert(textStatus)
      success: (data, textStatus, jqXHR) ->
        debugger;
        thisRef.self.html(thisRef.template(user: thisRef.user, order: data))

【讨论】:

  • thisRef 在成功中似乎不可用。收到此错误:show_view.self-3d520d9….js?body=1:45 Uncaught TypeError: thisRef.self.html is not a function
  • 我认为您在这里看到的问题不是 thisRef 不可用。就是 thisRef.self.html 不是一个函数。上面的赋值,@self = $el.html其实就是把html方法赋值给@self(this.self),所以调用,thisRef.self.html等价于$el.html.html ,这是我认为的问题。一种解决方案是将@self 分配改为@self = @$el。我将更新示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多