2011-12-28 2 views
0

프로젝트에서 나에게 더 잘 맞는 곳에서 더 나은 이해를 얻으려면 backbone.js 자료를 작성하려고합니다. 어떤 방식 으로든 사이트가 있으며 페이지 콘텐츠가 포함 된 컬렉션을로드하고 있습니다.backbone.js 초보자 컬렉션

JSON 데이터 내가이 "새로운 내용 없음에 ID 대신에 ({모델을 0을 넣으면 기본이

defaultRoute: function (actions) 
{ 
    this.showInfo('food'); 
}, 
showInfo: function (id) 
{ 
    var view = new ContentView({ model: this._items.at(id) }); 
    $(".active").removeClass("active"); 
    $("#" + id).addClass("active"); 
    view.render(); 
} 

내 라우터 (PID, 이름, 제목, 내용)으로 돌아 오면이를 ._items.at (0)}) "나는 컬렉션의 첫 번째 항목을 얻을 것이다 내가보기에이 작업을 수행 할 경우 :

var ContentView = Backbone.View.extend({ 
    el: $('#content'), 

    render: function() 
    { 
     this.el.empty(); 
     $(this.el).append(this.model.attributes.content); 
     return this; 
    } 
}); 

나는 내용이 완벽하게 표시되지만 물론 컨텐츠 I 파악하지 못할 수 있습니다 원했음

이름 == "food"를 기반으로 컬렉션에서 선택할 수 있습니까? 나는 ID 번호에 대한 내용이 DB에 저장하는 목적을 패배지도하고 싶지 해달라고

이 어리석은 질문처럼 보이지만 내가보고 간단한 임 확실 임 누락 뭔가 모든 것을 크롤 경우

죄송합니다

var NavigationRouter = Backbone.Router.extend({ 
    _data: null, 
    _items: null, 
    _view: null, 

    routes: { 
     "p/:id": "showInfo", 
     "*actions": "defaultRoute" 
    }, 
    initialize: function (options) 
    { 
     var _this = this; 
     $.ajax({ 
      url: "page_data.php", 
      dataType: 'json', 
      data: {}, 
      async: false, 
      success: function (data) 
      { 
       _this._data = data; 
       _this._items = new ItemCollection(data); 
       _this._view.render(); 
       Backbone.history.loadUrl(); 
      } 

     }); 

     return this; 
    }, 
    defaultRoute: function (actions) 
    { 
     this.showInfo('home'); 
    }, 
    showInfo: function (id) 
    { 
     var view = new ContentView({ model: this._items.at(id) }); 
     $(".active").removeClass("active"); 
     $("#l_" + id).parent().addClass("active"); 
     view.render(); 
    } 
}); 

답변

2

등뼈가 CollectionsUnderscore's 기능의 무리에 혼합하는 데 도움이 경우 여기에 내 전체 NavigationRouter 코드입니다. 당신이, 당신이 할 수있는 name === 'food' 컬렉션의 모델을 찾으려는 경우

그래서 :

var foodModel = this._items.find(function(model) { 
    return model.get('name') === 'food'; 
}); 
// this will set foodModel to the first model whose name is 'food' 

를 보조 노트로를, 당신은 단지 수, 당신의 렌더링 기능에 empty를 호출 할 필요는 없다 수 :

render: function() { 
    $(this.el).html(this.model.get('content')); 
    return this; 
} 

jQuery의 html 기능은 당신이에 전달하는 HTML 문자열 요소의 내용을 대체

+0

를 그래서 나는를 만들어야합니다. new var homeModel 등 각 페이지에 대해 this.whit이 NavigationRouter 외부에서 정의되지 않은 채로 내부 정보를 표시 할 예정입니다 – Ehask

+0

밑줄의'find' 함수를 사용하여 새 모델을 만들지 않습니다. 'this._items'에 이미 존재하는 모델을 찾아 참조를 저장하면됩니다. 그런 다음, 기존보기로 전달하거나 새로운보기로 전달할 수 있습니다. – satchmorun

+0

알았어요! 감사!! – Ehask

관련 문제