gpt4 book ai didi

javascript - Backbone Model 有条件地触发事件,View 听不到它

转载 作者:行者123 更新时间:2023-12-02 18:45:18 26 4
gpt4 key购买 nike

我正在创建一个地理位置模型,从 localStorage 获取数据,并检查那里是否有纬度属性。如果不存在,则会触发 'geolocation:city_state_blank' 事件。如果听到 'geolocation:city_state_blank',则会触发 @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:done 事件。

class App.GeolocationView extends Backbone.View
initialize: =>
@listenTo @model, 'geolocation:done', =>
alert('geolocation:done was heard in the view!!!!')

问题是这样的:

在这种情况下,本地理位置模型从 localStorage 获取并确定属性 latitude 未设置,从而调用 get_users_geolocation 时, View 警报地理定位:在 View 中听到完成!!!

但在 Geolocation 具有纬度属性(else)并立即触发 geolocation:done 的情况下, View 不会发出任何警报。 View 听不到它。

我已经控制台记录了这一切,并且可以说流路径正在工作。 if/else 正在工作,并且 View 正在正确实例化。从 localStorage 获取后在回调中记录会产生此..

@fetch().always => 
console.log @get('current_city_state')
console.log typeof @get('current_city_state')
// Norfolk, VA
// String

所以,那里有数据..

这是怎么回事??请帮忙!!

最佳答案

我猜您的 App.GeoLocationlatitude 属性是一个数字。这会让你的测试看起来像这样:

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有一个p,以及no no

演示:http://jsfiddle.net/ambiguous/qmBNy/

关于javascript - Backbone Model 有条件地触发事件,View 听不到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16445438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com