2012-06-27 4 views
1

간단하지만 혼란스러운 문제가 있습니다. 이 오류가 발생합니다백본보기의 모델이 누락되었지만 이유를 이해할 수 없습니다.

<div id="restaurant_locations"></div> 

<script type="text/javascript"> 
    $(function() { 
    window.router = new Lunchhub.Routers.RestaurantLocationsRouter({ 
     restaurantLocations: <%= @restaurant_locations.to_json.html_safe -%> 
    }); 
    Backbone.history.start({pushState: true}); 
    }); 
</script> 

: 나는 다음과 같은 코드 조각이 나는 그래도 {pushState: true} 부분을 가지고가는 경우에

Uncaught TypeError: Cannot call method 'toJSON' of undefined 

을 그냥 인수없이 Backbone.history.start() 할, 그냥 잘 작동합니다.

오류 옆에 show_view.js: 19이 표시됩니다.

ShowView.prototype.template = JST["backbone/templates/restaurant_locations/show"]; 

    ShowView.prototype.render = function() { 
     $(this.el).html(this.template(this.model.toJSON())); // LINE 19 
     Uncaught TypeError: Cannot call method 'toJSON' of undefined 
     return this; 
    } 

그래서 내가 this.model가 정의되지 않은 추측 : 여기처럼 show_view.js의 일부가 보이는거야. 여기에 show_view 커피 스크립트는 다음과 같습니다

Lunchhub.Views.RestaurantLocations ||= {} 

class Lunchhub.Views.RestaurantLocations.ShowView extends Backbone.View 
    template: JST["backbone/templates/restaurant_locations/show"] 

    render: -> 
    $(@el).html(@template(@model.toJSON())) 
    return this 

나는이 문제를 해결할 수있는 생각, @model 그것을 할 필요가 무엇을 할 수 있도록 할 수 있습니다. 그러나 나는 @model이 어디서 온 것인지 알지 못합니다.

무엇을해야합니까?

편집 : 조금 더 있습니다. 아래의 show 함수에서 id은 "restaurant_locations"로 설정되고 물론 restuarant_locations의 ID를 가진 @restaurantLocations의 구성원은 없습니다. id 세트가 restaurant_locations으로 설정된 사실은 어느 정도 의미가 있습니다. 내가 치는 URL은 http://localhost:3000/restaurant_locations입니다. 그러나 index 함수가 아닌 show이 아니라면이 URL이 내가가는 URL 인 것 같습니다. 내가 거기에 몇 가지 문제를 참조

routes: 
    "new"  : "newRestaurantLocation" 
    "index" : "index" 
    ":id/edit" : "edit" 
    ":id"  : "show" 
    ".*"  : "index" 

: 당신이 그렇게 저희가 귀하의 경로를 살펴 보자 라우팅 문제를 가지고있는 것처럼

class Lunchhub.Routers.RestaurantLocationsRouter extends Backbone.Router 
    initialize: (options) -> 
    @restaurantLocations = new Lunchhub.Collections.RestaurantLocationsCollection() 
    @restaurantLocations.reset options.restaurantLocations 

    routes: 
    "new"  : "newRestaurantLocation" 
    "index" : "index" 
    ":id/edit" : "edit" 
    ":id"  : "show" 
    ".*"  : "index" 

    newRestaurantLocation: -> 
    @view = new Lunchhub.Views.RestaurantLocations.NewView(collection: @restaurantLocations) 
    $("#restaurant_locations").html(@view.render().el) 

    index: -> 
    @view = new Lunchhub.Views.RestaurantLocations.IndexView(restaurantLocations: @restaurantLocations) 
    $("#restaurant_locations").html(@view.render().el) 

    show: (id) -> 
    restaurant_location = @restaurantLocations.get(id) 

    @view = new Lunchhub.Views.RestaurantLocations.ShowView(model: restaurant_location) 
    $("#restaurant_locations").html(@view.render().el) 

    edit: (id) ->     
    restaurant_location = @restaurantLocations.get(id) 

    @view = new Lunchhub.Views.RestaurantLocations.EditView(model: restaurant_location) 
    $("#restaurant_locations").html(@view.render().el) 
+0

'showVideo.model'은 '새로운 ShowView ({model : myModelInstance})'에서 가져옵니다. 미안하지만 훨씬 간단한 시나리오에서 백본으로 조사를 시작해야한다는 것을 모르는 경우에는 꼭 말해야합니다. – fguillen

+0

당신은 copypasta 했습니까? – jakee

+0

필자가 언급 했어야 할 것은 : 저는 레일즈에 있고 백본 레일 (backbone-rails) 젬을 사용하고 있습니다.이 젬은 자동으로 많은 코드를 생성합니다. 나는 그것이 생성 된 코드를 디버깅하지 않고도 작동 할 것이라고 기대할 수 있지만, 그렇다고 밝혀지지는 않았다. –

답변

0

id is set to "restaurant_locations" , and there's of course no member of @restaurantLocations with an id of "restuarant_locations" .

는 소리. 우선, 경로가 정규 표현식이 아니므로 /.*/ (즉, 임의의 문자 시퀀스)과 일치하지 않으므로 모든 마침표 (즉, /^.*$/)와 실제로 일치합니다. 당신은 '.*'에 어떻게되는지 _routeToRegex 자신을 통해 그것을 실행할 수 있습니다

var namedParam = /:\w+/g; 
var splatParam = /\*\w+/g; 
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; 
//... 
_routeToRegExp: function(route) { 
    route = route.replace(escapeRegExp, '\\$&') 
       .replace(namedParam, '([^\/]+)') 
       .replace(splatParam, '(.*?)'); 
    return new RegExp('^' + route + '$'); 
}, 

다음 문제는 ":id" 거의 모든 항목과 일치한다는 것입니다. routeToRegexp":id"/^([^/]+)$/으로 변환합니다. 그 정규식은 비 - 슬래시의 비어 있지 않은 시퀀스와 일치하며 특히 다른 대부분의 라우트가 일치하는 것과 일치합니다.

그래서 당신은 당신이 실제로 ':id': 'show'을 타격하고 당신은 '/new''/index'':id' 일치지고도없는 운지고있어, /restaurant_locations에서 '.*': 'index'을 칠 것으로 예상 할 때. (Java | Coffee) Script 객체의 요소 순서는 구현 정의이므로 소스 코드에 나타나는 순서는 중요하지 않습니다. 많은 JavaScript 구현은 소스 순서를 존중하지만 절대 의존하지 않습니다.

경로 순서가 중요하지 않으므로 routes 키를 단순한 정렬되지 않은 세트로보아야하고 사용자 (사람)가 경로 패턴이 실제로 별개의 항목과 일치하는지 확인해야합니다. 겹치는 경로 패턴이 필요하고 특정 순서로 일치해야하는 경우 라우터의 initialize에있는 route 메소드를 사용하여 경로를 라우팅 순서 또는 정규식으로 수동으로 필요한 순서로 추가 할 수 있습니다.


요약 : 그들은 별개의 일을 일치하도록 당신의 경로를 수정합니다.

+0

감사. ''index '': "restaurant_locations"'라는 새로운 경로를 추가하여 문제를 해결할 수있었습니다 (즉, 오류없이 페이지가로드되도록). 하단에 새로운 경로를 추가해도 아무 것도하지 않았으므로 상단에 추가하면 경로 순서가 실제로 중요해 보입니다. –

+0

@JasonSwett : 출처의 경로 순서에 따라 도박이 가능하다는 보장은 없습니다. 소스 순서에 따라 브라우저 의존적 인 버그를 스스로 해결할 수 있습니다. JavaScript 표준은 객체의 키에 대한 반복이 소스 순서로 키를 생성한다고 보장하지 않습니다 (http://stackoverflow.com/a/10624559/479863). –

관련 문제