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