2014-04-14 3 views
1

나는 여기에 간단한 것을 놓치고 있지만 다음은 작동하지 않는 것 같습니다.Emberjs의 같은 클래스에서 다른 메서드를 호출하는 방법

App.Storage = Ember.Object.extend 

    push: (key, data)-> #I want to call this from the loop below in pushMany 
    #... 
    #... 

    pushMany: (key, data)-> 

    data.forEach (d)-> 
     #Tried: 
     @push(key, d) #<< TypeError: undefined is not a function 
     #Also tried: 
     @send('push', key, d) #<< TypeError: undefined is not a function 
     #Also tried: 
     App.Storage.push(key, d) #<< TypeError: undefined is not a function 

나는 경로에 pushMany를 호출 오전 :

App.MessagesRoute = Ember.Route.extend 
    setupController: (controller, model)-> 
    #storage is injected to route 
    #I can call storage.push here so I'm pretty sure my injection is working properly 
    storage = @get('storage') 
    storage.pushMany 'message', [{id: 3, value: 'Test Msg', author: 'Jules'}, {id: 4, value: 'Hello World!', author: 'Jules'}] 

이제 시간 동안 갇혀 있었다. 어떤 도움을 주시면 감사하겠습니다.

답변

1

귀하의 문제는 대상 범위입니다. 여기

예 :

var Test = Ember.Obejct.extend({ 
    func: function(){ 
    // the scope of "this" is the Test object 
    this.get('data'); 

    var self = this; 

    this.get('data').forEach(function(){ 
     // "this" is now the closure 
     // use "self" to access it 
     self.set('data', 'blup'); 

    }); 
    }   
}); 

귀하의 경우 :

App.Storage = Ember.Object.extend 
    pushMany: (key, data)-> 
    self = this 
    data.forEach (d)-> 
     self.push(key, d) 

여기를 참조하십시오 : How do JavaScript closures work?

+0

흠 ... pushMany 함수에서'data'와'key'가'function' 매개 변수 인'set'을'접근'하고'데이터'를 사용하려하지 않았습니다. 내가 액세스하고자하는 것은'pushMany' 함수 안에있을 때'push' 함수입니다. 아니면 당신이 설명하고 싶은 것을 오해 했습니까? –

+0

내 답변에 케이스를 추가했습니다. – medokin

+0

마술처럼 작동합니다! : D 나는'self = this'를 사용한 적이 없으며'this'는 항상 사용하기 때문에 제대로 사용하는 방법입니다. 감사! : D –

0

문제는 Ember 방식을 벗어난 매우 중요한 작업입니다. 대신 값을 저장하는 App.Storage를 사용하는 단지 모델 후크를 수행

App.MessageRoute = Ember.Route.extend({ 
    model:function() { 
     return [{id: 3, value: 'Test Msg', author: 'Jules'}, {id: 4, value: 'Hello World!', author: 'Jules'}] 
    }, 
    actions: { 
     addMessage:function() { 
      this.get('model').pushObjects({id:5,value:'Heya',author:'Nick'}); 
     } 
    } 
}); 
+1

오해 받아서 죄송합니다. 방금 '푸시'메서드를 호출하는 방법을 알고 싶었 기 때문에 메시지 캐싱을 위해 App.Storage에 HTML5 localStorage를 사용하고있는 것과 같은 기타 불필요한 세부 사항은 생략했습니다. 따라서 나는이 방법을 사용할 수 없습니다. 하지만 답장을 보내 주셔서 감사합니다. –

0

을이 스레드는 미래의 여행자는 참조 용으로 너무 최근의 것이 아니라 :

I을 같은 문제가있었습니다 (저는 CoffeeScript를

:이 thisforEach() 방법의 범위는 것을 의미, 다음으로 "컴파일"됩니다

:

문제는 그가 data.forEach (d)->을 사용하고 있다는 사실이다 : 저자)과는 것을 알아 냈

실제로

data.forEach(function(d) { 
    this.push(key, d); 
    this.send('push', key, d); 
    return App.Storage.push(key, d); 
}); 
, 그것은 이런 식으로 "컴파일"해야합니다

this.data.forEach((function(_this) { 
    function(d) { 
     // your code here, using '_this' and 'd' 

     _this.push(key, d); 
     _this.send('push', key, d); 
     return App.Storage.push(key, d); 

    }; 
    })(this)); 

도움 resou을 순위 :

관련 문제