主干get属性返回未定义

Backbone get attributes returns undefined

本文关键字:未定义 返回 属性 get 主干      更新时间:2023-09-26

我已经得到了我的骨干模型定义如下:

define (require) ->
 Backbone = require 'backbone'
 class IndexModel extends Backbone.Model
  defaults:
    status: ""
    country: ""
    language: "" 
  initialize: (attributes,options) ->
    @set 'country', attributes.country
    @set 'language', attributes.language ||= 'en'
  url: -> "/v0/index/#{@get 'country'}/#{@get 'language'}.json"

然后我的视图是这样的:

define (require) ->
 Backbone = require 'backbone'
 template = require 'text!templates/index-page.html'
 IndexModel = require 'cs!models/index'
class IndexView extends Backbone.View
  template: _.template(template)
  el: 'article.main'
  events:
   "click .image_button": "connect"
  initialize: ->
    _.bindAll(@, "render","connect")
    @render()
  render: ->
    @$el.html(@template)
  connect: (e) ->
   @model = new IndexModel({country: e.currentTarget.alt, language: window.language})
   @model.save()
   console.dir @model
   console.log 'Status: ', @model.get 'status
   no

我试图获得状态属性,但它似乎是空的,返回未定义。

我哪里做错了?

我假设在服务器上设置了'status'属性。如果是,则model.save()调用是异步的,并且该属性在调用完成之前是不可用的。要访问它,您需要绑定到调用save时传递的成功回调,例如:

_self = @
@model.save success: ->
  console.log 'Status: ', _self.model.get('status')

或者你可以绑定到模型上的'sync'事件,它将在每次成功保存后触发,例如:

@model.on 'sync', (model) ->
  console.log 'Status: ', model.get('status')

@robmisio非常感谢您的回复,我尝试了您的两个建议,但没有一个适合我。我用这个工作……

connect: (e) ->
  @model = new IndexModel({country: e.currentTarget.alt, language: window.Language})
  $('#spinner_ajax').show()
  @model.save(null, {
    success: @success
    error: @error
  })
error: (xhr, status, thrown) ->
  console.log "AJAX Error: #{status}"
  alert "AJAX Error: #{status}: Server is probably down."
  $('#spinner_ajax').hide();
  no
success: (model) ->
  console.log "Status: #{model.get('status')}"
  if model.get('status')
    window.lmStatus = true
    window.location.hash = 'connection'
    $('#spinner_ajax p').html('You are being redirected ')
  else
    alert 'This connection is currently not active.'
    $('#spinner_ajax').hide();
  no