我的骨干模型定义如下:
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
我正在尝试获取状态属性,但它似乎是空的并且返回未定义。
我在这里做错了什么?
答案 0 :(得分:2)
我假设在服务器上设置了'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')
答案 1 :(得分:0)
@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