2012-05-24 4 views
0

이 함수 (*)와 (**)는 Backbone.View 안에 있지만이 문제를 해결하는 데 Backbone에 대한 지식이 필요하지 않다고 생각합니다. 때 코드에서 내 의견에서 볼 수 있듯이이 코드 조각을 다시 작성하는 방법

:
1) 나는 getAvatar 기능 모든 것이 괜찮 전화 2
)이 getAvatar는 setAvatar 뭔가 내가 해결 방법을

깨 호출 할 때 다음 문제?


(*)

getAvatar: function() 
    { 
     var creatorIds = this.getCreatorIds(); 
     console.log(creatorIds); // [1,2] ****** here is ok ******* 

     for (var c = 0, l = creatorIds.length; c < l; c += 1) { 
      if (typeof this.avatars[creatorIds[c]] === 'undefined') { 
       this.userModel = new UserModel({id: creatorIds[c]}); 
       this.userModel.fetch(); 
       this.userModel.on('change', this.setAvatar, this);  
      } 
     } 
    }, 

(**)

setAvatar: function() 
    {  
     console.log(this.userModel.get('id')); // 2, 2 ********* it should be 1, 2 ******* 
     this.names[this.userModel.get('id')] = this.userModel.get('name'); 
     this.avatars[this.userModel.get('id')] = typeof this.userModel.get('avatar'); 
     this.render(); 
    }, 

(*)

,
initialize: function() 
{ 
    _.bindAll(this, 'getAvatar', 'setAvatar'); 
} 
+0

, 당신도 함수의 범위를 바인딩? '_.bindAll (this)'또는 비슷한 것? – rjz

+0

루프의 this.userModel 값을 겹쳐 쓰고 있습니다. 'context'를'.on'의 셋째 매개 변수로 제공하고 setAvatar에서'this'를 정확히'UserModel' 인스턴스로 설정할 수 있습니다. –

+0

@Darhazer 당신이 제안한 것을 시도했지만 똑같은 결과를 얻었습니다. this.userModel에 관한 것입니다. 어떻게 생각해? – js999

답변

1

는 backbone.js처럼 코드가

getAvatar: function() 
{ 
    var creatorIds = this.getCreatorIds(); 
    console.log(creatorIds); // [1,2] ****** here is ok ******* 

    for (var c = 0, l = creatorIds.length; c < l; c += 1) { 
     if (typeof this.avatars[creatorIds[c]] === 'undefined') { 
      this.userModel = new UserModel({id: creatorIds[c]}); 
      this.userModel.fetch(); 
      this.userModel.on('change', this.setAvatar, this); //added this after the function. 
     } 
    } 
}, 

on

object.on(event, callback, [context]) 

에 대한 상황에 대한 세 번째 매개 변수가 또는 폐쇄

getAvatar: function() 
{ 
    var that = this; //variable to maintain scope 
    var creatorIds = this.getCreatorIds(); 
    console.log(creatorIds); // [1,2] ****** here is ok ******* 

    for (var c = 0, l = creatorIds.length; c < l; c += 1) { 
     if (typeof this.avatars[creatorIds[c]] === 'undefined') { 
      this.userModel = new UserModel({id: creatorIds[c]}); 
      this.userModel.fetch(); 
      this.userModel.on('change', function(){ that.setAvatar(); }); //use a closure here with that variable that which is defined above.  
     } 
    } 
}, 
+0

나는 당신이 제안한 것과 똑같은 문제를 얻으려고 노력했다. 어쨌든, 문제를 재현하기 위해 jsfiddle.net을 만들려고 노력할 것이다. – js999

+0

나는 문제가 문맥이 아니라 동일한 변수를 두 번 할당했기 때문에 -1을 할당합니다. 어쨌든 저는 90 점을 받았으며 투표를 할 수 없습니다. – js999

+0

@ js999 동일한 변수를 두 번 할당하는 경우이를 배열로 만듭니다. 새 항목을 끝까지 밀어 넣으십시오. – epascarello

1

를 사용할 수 있습니다 같은데 문제는 동일한 변수를 두 번 할당한다는 것입니다. getAvatar()에서 먼저 다음 루프 반복에서 다음 아이디 == 1로 UserModel에 this.userModel을 설정합니다, 그것은 아이디 ==와 UserModel 할당됩니다 2.

setAvatar() 기능이 충돌하는 경우, 그것은 것입니다 this.userModel을보고 설정 한 값만 확인하십시오. 모델을 저장하기 위해 인스턴스 변수를 사용하지 않도록 노력해야합니다.

수정 방법은 다음과 같습니다. 아마 그것을 고칠 수있는 더 쉬운 방법이 있지만, 주어진 코드 샘플로부터 알기는 어렵습니다. 또한 코드의 이상한 점에 대해 몇 가지 의견을 추가했습니다.

(*) initialize``에서

getAvatar: function() 
{ 
    var creatorIds = this.getCreatorIds(); 
    console.log(creatorIds); // [1,2] ****** here is ok ******* 

    var self = this; 

    for (var c = 0, l = creatorIds.length; c < l; c += 1) { 
     if (typeof this.avatars[creatorIds[c]] === 'undefined') { 
      var user = new UserModel({id: creatorIds[c]}); 

      //probably better to bind the handler first, in case fetch() completes synchronously from cache 
      user.on('change', function(){ 
       console.log(user.get('id')); 
       self.names[user.get('id')] = user.get('name'); 
       self.avatars[user.get('id')] = typeof user.get('avatar'); //are you sure you want typeof here? 
       self.render(); //Note, this will get called a lot. Are you sure you want to do this? 
      }); 

      user.fetch(); 
     } 
    } 
} 
+0

당신은 절대적으로 맞습니다 .. 시간 내 주셔서 감사합니다 – js999

+0

그게 해결책이라면 올바른 답으로 표시해야합니다. –

+0

알아, 걱정하지 마. 어쨌든 +1 왜냐하면 내가 같은 변수를 두 번 지정하고 있다고 말하는 것이 맞지만 코드에 클로저 문제가 있다고 생각합니다. – js999

관련 문제