2012-05-03 2 views
1

ID가 미리 입력 된 서버에 새 모델을 추가하려는 경우 .save()가 잘못된 isNew() 값을보고하는 문제가 발생했습니다. . 그게 내가 그것을 지키고 model.id를 수동으로 설정하도록 유도했다. 내가 잘 collection.getByCid (CID)를 통해 그렇게 할 수 있어요하지만 내가 collection.get (ID)를 사용하여 모든 레코드를 검색 할 수 없습니다 나는이 시점에서backbone.js collection.get (id) returns undefined

RecordListItemView = Backbone.View.extend({ 
     initialize:function() { 
      var record = this.model.attributes; 
      if (record.user_id) { 
       this.model.id = parseInt(record.user_id); 
       record.id = parseInt(record.user_id); 
        // Added this so ID would show up in model and .attributes 
      } 
      this.model.bind("change", this.render, this); 
      this.model.bind("destroy", this.close, this); 
     }, 

     render:function (eventName) { 
      $(this.el).html(this.template(this.model)); 
      console.log(this); 
      return this; 
     } 
    }); 

:

여기 내보기입니다.

d 
     $el: e.fn.e.init[1] 
     cid: "view36" 
     el: HTMLLIElement 
     model: d 
     _callbacks: Object 
     _escapedAttributes: Object 
     _pending: Object 
     _previousAttributes: Object 
     _silent: Object 
     attributes: Object 
     id: 15 
     user_id: "15" 
     user_name: "Test" 
     __proto__: Object 
     changed: Object 
     cid: "c8" 
     collection: d 
     id: 15 
     __proto__: x 
    options: Object 
    __proto__: x 

의 ID 필드를 포함하는 내 데이터베이스를 변경하지 않고 collection.get (ID)를 고정 할 수있는 방법이 있나요 :

여기 내 CONSOLE.LOG 출력입니까? 벤자민 콕스 아래 게시 된

(현재 PK로 USER_ID 사용) (필요로 제거으로 parseInt()와 함께)

바꾸기

this.model.id = record.user_id; 

this.model.set({ id: record.user_id }); 

와 .. Model의 변경 이벤트를 우회하여 Collection의 internal_byId [] 배열을 업데이트하지 않도록합니다.

은 모두 테스트 후에, 나는 모델을 찾을 수없는 collection.get (ID)를 호출하는 것은 당신이 걸이다 ..

parse: function(response) { 
     return { 
      id: response.user_id, 
      user_id: response.user_id, 
      user_name: response.user_name 
     }; 
    } 

답변

2

MU가 너무 짧은 parse 제안이다 사용하는 이유를 상처 백본의 이벤트 메커니즘을 우회 당신이 할 때

this.model.id = parseInt(record.user_id); 

이 대신 할 경우 :

this.model.set({ id: parseInt(record.user_id)}); 

그러면 모델의 set() 메서드에있는 백본 이벤트 코드가 "change : id"이벤트를 시작합니다. 컬렉션은 차례로이 이벤트를 수신하고 내부 _byId [] 배열 변수를 업데이트합니다. 나중에 collection.get (id)를 호출하면이 배열을 사용하여 일치하는 모델을 검색합니다.

+0

서버에서 가져올 때'user_id'를'id'로 복사하는 ['parse'] (http://documentcloud.github.com/backbone/#Model-parse) 구현을 추가하는 것도 좋은 생각 일 수 있습니다 . –

+0

Benjamin - 그건 의미가 있습니다. 내일 사무실에 들어가 자마자 시험해 보겠습니다. 무언가 -'parse'에 대한 연구가 필요 하겠지만, 데이터를 해킹하는 것보다 백본 방법을 사용하는 것이 훨씬 낫습니다. 둘 다 고마워. – Rosseyn

+0

귀하의 제안에 감사드립니다. 그들은 깨끗하게 정리했습니다! – Rosseyn