2014-05-21 4 views
0

knockout.js를 배우고 jsfiddle에서 흥미롭고 유용한 샘플을 많이 찾습니다. 나는 일부 knockout.js 샘플을 사용하여 object.prototype을 사용하여 viewmodel 객체에 메서드를 추가합니다. 일부 샘플에서는 viewmodel에 메소드를 정의하고 .bind (this)를 사용하지만 다른 샘플에서는 그렇지 않습니다. 그래서 나는 prototype을 사용하여 추가 된 메소드로 .bind (this)를 사용해야 할 때를 이해하지 못한다.knockoutjs 프로토 타입에서 .bind (this)를 사용하는 경우

예를 들어 this sample은 프로토 타입을 사용하여 ViewModel 객체에 몇 가지 메소드를 추가하지만 viewmodel의 메소드도 정의한 다음 .bind (this)를 사용합니다. 내가 왜 another sample viewmodel과 같은 메서드를 선언하지 않습니다 .bind (this)이 발견 할 필요가 이해가 안 돼요.

var ViewModel = function(items) { 
    this.selectItem = this.selectItem.bind(this); 
    this.acceptItem = this.acceptItem.bind(this); 
    this.revertItem = this.revertItem.bind(this); 
} 
ko.utils.extend(ViewModel.prototype, { 
    //select an item and make a copy of it for editing 
    selectItem: function(item) { 
     this.selectedItem(item); 
     this.itemForEditing(new Item(ko.toJS(item))); 
    }, 

    acceptItem: function(item) { 
     if (item.errors().length == 0) { //Check if ViewModel has any errors 
      alert('Thank you.'); 
     var selected = this.selectedItem(), 
      edited = ko.toJS(this.itemForEditing()); //clean copy of edited 

     //apply updates from the edited item to the selected item 
     selected.name.update.call(selected, edited); 

     //clear selected item 
     this.selectedItem(null); 
     this.itemForEditing(null); 
     } 

     else { 
      alert('Please check your submission.'); 
      item.errors.showAllMessages(); 
     } 
    }, 

    //just throw away the edited item and clear the selected observables 
    revertItem: function() { 
     this.selectedItem(null); 
     this.itemForEditing(null); 
    } 
}); 

답변

1

JavaScript에는 다른 언어와 같은 방법 개념이 없습니다.

> var f = new Foo() 
> f.bar() 
This is { foo: 12, bar: [Function] } and this.foo is 12 

그러나 f.bar 정말되지 않습니다 : 당신이 var f = new Foo()으로 새 인스턴스를 만들 때

function Foo() { 
    this.foo = 12; 
    this.bar = function() { 
     console.log('This is', this, 'and this.foo is', this.foo); 
    }; 
} 

, 당신은 함수 될 일이 그 bar 특성, 호출 할 수 있습니다 :이 객체를 고려 메서드는 바운드와 언 바운드 모두 될 수있는 Python 메서드와 같은 메서드입니다. 객체의 속성 될 일이 자바 스크립트 함수는 항상 언 바운드 :

f의 속성으로 호출되지
> var b = f.bar 
> b() 
This is Window {...} and this.foo is undefined 

, this는 루트 객체가됩니다.

> b.call(f) 
This is { foo: 12, bar: [Function] } and this.foo is 12 

당신이 .bind를 사용하여 특정 thisf.bar 바인딩 할 수 있습니다, 바인딩 방법처럼 f.bar 자세한 내용을 확인하려면, 그래서 앞의 예 : 실제로, f.bar()를 호출하면 암시과 같이, ff.barthis 개체를 가져 오거나 설정 예상대로 작동합니다.

+0

답장을 보내 주셔서 감사합니다. 그것은 .bind 함수와 언제 사용하는지에 대한 아주 좋은 설명을 제공합니다. 그러나 나는 한 샘플에서 왜 사용 되었는가에 대해 혼란스러워하며 다른 샘플에서 사용되지 않은 이유는 둘 다 똑같은 일을하고 있습니다. 프로토 타입을 사용하고 'this'를 사용하여 다른 멤버에 액세스합니다. 내가 그것을 제거하고 viewmodel에서 함수 선언을 제거하고 다른 샘플에서 수행 된 것과 비슷한 방식으로 수행하는 경우 '.bind'를 사용하는 샘플에서는 작동하지 않습니다. 그래서 이유가 있으며 그 이유를 알고 싶습니다. – Hitesh

관련 문제