[英]Backbone Model triggers event conditionally, View doesn't hear it
我正在创建一个地理定位模型,从localStorage获取,并检查我是否有纬度属性。 如果没有,则触发'geolocation:city_state_blank'
事件。 如果听到'geolocation:city_state_blank'
, @get_users_geolocation()
触发@get_users_geolocation()
。
class App.GeoLocation extends Backbone.Model
initialize: ->
@on 'geolocation:city_state_blank', -> @get_users_geolocation()
@fetch().always =>
if @get('city_state').length is 0
@trigger 'geolocation:city_state_blank'
else
@trigger('geolocation:done')
get_users_geolocation: =>
# Code to get / save (in localStorage) a users geolocation and city / state
@trigger('geolocation:done')
完成get_users_geolocation()
之后,触发事件geolocation:done
。
我已经删除了获取用户geoLocation / reverse Geolocation查找的详细信息,这些查找都是异步的。 但是所有这些工作的最终结果归结为触发geolocation:done
事件。
class App.GeolocationView extends Backbone.View
initialize: =>
@listenTo @model, 'geolocation:done', =>
alert('geolocation:done was heard in the view!!!!')
在Geolocation模型从localStorage获取并确定未设置属性latitude
情况下,因此调用get_users_geolocation
- 视图警报地理位置:在视图中听到完成!!!!
但是在Geolocation具有纬度属性(else)并触发geolocation:done
,View 不会发出任何警报。 视图没有听到。
我已经控制了。记住了这个地狱,并且可以说流路正在运行。 if / else正在运行,View正在被正确实例化。 从localStorage获取后在回调中记录产生这个..
@fetch().always =>
console.log @get('current_city_state')
console.log typeof @get('current_city_state')
// Norfolk, VA
// String
那么,那里有数据..
到底是怎么回事?? 请帮助!!
我猜你的App.GeoLocation
的latitude
属性是一个数字。 这会让你的测试看起来像这样:
if some_number.length is 0
数字没有length
属性,所以@get('latitude').length
将是未定义的,你留下:
if undefined is 0
这总是假的,所以@trigger('geolocation:done')
总是被调用。
如果您对latitude
属性的存在感兴趣,那么CoffeeScript的存在运算符( ?
)将为您提供更好的服务:
if @get('latitude')?
# There is a latitude.
else
# No latitude.
看怎么样?
表现你可以看看这是做什么的:
class M extends Backbone.Model
m = new M(p: 0)
if m.get('p') == 0
console.log('p == 0')
else
console.log('p != 0')
if m.get('p')?
console.log('there is a p')
else
console.log('the p is a lie')
if m.get('no')?
console.log('yes no')
else
console.log('no no')
这将给你p == 0
, there is ap
, no no
。
我最终这样做了。 它不漂亮,但它的工作原理。
@listenTo @model, 'geolocation:done', =>
@prefill_location_input()
@initialize_autocomplete()
@prefill_location_input()
@initialize_autocomplete()
我认为你的权利,事件是在init返回之前触发的。 这里,如果Object立即就绪,则@prefill_location_input()
和@initialize_autocomplete()
, geolocation:done
将在从网络中获取的情况下覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.