tailieunhanh - Phát triển Javascript - part 27

Tham khảo tài liệu 'phát triển javascript - part 27', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Error Handling 233 By throwing an exception already when adding the observers we don t need to worry about invalid data later when we notify observers. Had we been programming by contract we could say that a precondition for the addObserver method is that the input must be callable. The postcondition is that the observer is added to the observable and is guaranteed to be called once the observable calls notifyObservers. The test fails so we shift our focus to getting the bar green again as quickly as possible. Unfortunately there is no way to fake the implementation this time throwing an exception on any call to addObserver will fail all the other tests. Luckily the implementation is fairly trivial as seen in Listing . Listing Throwing an exception when adding non-callable observers function addObserver observer if typeof observer function throw new TypeError observer is not function observer addObserver now checks that the observer is in fact a function before adding it to the list. Running the tests yields that sweet feeling of success All green. Misbehaving Observers The observable now guarantees that any observer added through addObserver is callable. Still notifyObservers may still fail horribly if an observer throws an exception. Listing shows a test that expects all the observers to be called even if one of them throws an exception. Listing Expecting notifyObservers to survive misbehaving observers test should notify all even when some fail function var observable new var observer1 function throw new Error Oops var observer2 function true observer1 observer2 assertTrue Download from 234 The Observer Pattern Running the test reveals that the current implementation blows up along with the first observer causing the second observer not to be called. In effect .

TỪ KHÓA LIÊN QUAN
crossorigin="anonymous">
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.