2012-06-14 67 views
0

无法设置模型 - 骨干

class FoursquareSearch.Views.Origin extends Backbone.View 

events: 
    'change [name=origin]': 'setOrigin' 
    'click [name=geolocate]' : 'geolocate' 

    geolocate: -> 
    navigator.geolocation.getCurrentPosition(@handle) 

    handle: (response) -> 
    @model.set(coords: response) 

我试图确定设备的位置,然后设置与响应模型视图。不过我得到

Uncaught TypeError: Cannot call method 'set' of undefined 

奇怪的是这只发生在它的这个函数里面。例如,如果我使用:

geocode: (location) -> 
    data = 
     location: location 

    $.ajax(
     type: 'POST' 
     url: '/search/geocode' 
     data: data 
     dataType: 'json' 

     error: (jqXHR, textStatus, errorThrown) => 
     alert("ERROR") 


     success: (response, text, xhr) => 
     @model.set(coords: response) 
     @center(@model.get('coords')) 
     ) 

里面它的工作原理相同的观点,以及它工作得很好。不过我只是不能得到其他功能设置模式。我认为这是关于它异步的东西。我绝不是这方面的专家,我正在捡拾Backbone,但是这让我难受!

回答

2

Geolocation API不指定getCurrentPosition回调函数任何特定的上下文,以便this回调里面可能是window; window通常不会有model属性,因此这样的:

handle: (response) -> 
    @model.set(coords: response) 

最终看起来像这样当getCurrentPosition调用它:

handle: (response) -> 
    window.model.set(coords: response) 

所以handle试图呼吁不存在window.modelset和有你的Cannot call method 'set' of undefined错误。

尝试定义handlebound method

handle: (response) => # fat arrow here 
    @model.set(coords: response) 

你的其他@model.set呼叫工作正常,因为@是您的视图对象和确实有model财产。

+0

这真棒谢谢 –