2014-12-29 1 views
0

Backbone Views에서 일반적인 패턴을 사용합니다. 거의 모든 경우에 모든 이벤트 처리기를 해당 이벤트 객체가 아닌보기에 바인딩하려고합니다. 다음과 같은 이벤트 객체가 있습니다. 이렇게하면 :이름 배열을 _.bindAll에 전달 - 인수 목록의 유형이 잘못되었습니다

initialize: function(){ 
    _.bindAll(this, 'click_removeToken', ...); 
} 

모든 이벤트 이름을 수동으로 나열해야합니다.

_.bindAll(this, _.values(this.events)); 

밑줄이 각각의 이름은 인수가 아닌 배열로 전달되고 싶어 : 우리는 단순히 배열을 전달하지만,이 사용을 활성화하지 않습니다 강조 수 있다면 이상적 일 것이다. 그러나이 또한 작동하지 않습니다 : 그것은 모든 기능을 나열 수동으로 요구하지 않도록하는 좋은 방법에

"Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type" 

어떤 아이디어가 bindAll의 사용을 단순화하기 :

_.bindAll.apply(this, _.values(this.events).unshift(this)); 

자바 스크립트는이 오류를 제공합니다 구속 할 이름?

+0

더있다 당신은 배열 참조를 저장 위치를 ​​수정 한 다음 apply 해당 참조를 전달 또는 다른 속임수를 사용하지 않으려면 하나 필요 그렇게해야합니다. 백본은'events' 해시에서 호출 된 메소드에 대한 인스턴스의 컨텍스트를 자동으로 할당합니다 –

답변

3

수정 된 배열의 길이 인 unshift의 리턴 값인 bindAll을 전달하고 있습니다.

// note, no need to bind to `this` 
_.bindAll.apply(null, [this].concat(_.values(this.events))); 

짧은 예 :

var target = document.querySelector('#target'); 
 

 
var map = { 
 
    'foo': 'foo', 
 
    'bar': 'bar' 
 
}; 
 

 
function C() { 
 
    this.value = 'Value'; 
 
    _.bindAll.apply(null, [this].concat(_.values(map))); 
 
} 
 

 
C.prototype.foo = function() { 
 
    console.log('hello', this); 
 
    target.textContent = this.value + ' set by foo'; 
 
} 
 

 
C.prototype.bar = function() { 
 
    return this.value; 
 
} 
 

 
var c = new C(); 
 

 
document.addEventListener('click', c.foo);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script> 
 

 
<div id="target">Click me</div>

+0

컨텍스트가 여전히 '_'이면 안됩니까? – Mathletics

+1

@Mathletics 아니요, 'bindAll'은 실제로'this'에 대한 참조를 사용하지 않습니다. 순수 함수입니다. –

+0

아 물론. 편집이 좋아 보인다. – Mathletics