dispose: ฟังก์ชันนี้จะถูกเรียกเมื่อองค์ประกอบ DOM ถูกลบออกจาก DOM
ตัวอย่างเช่น:
1 2 3 4 5 6 7 8 9 10 11
ko.bindingHandlers.myBinding = { init: function(element, valueAccessor, bindingContext) { // Do something when the element is created }, update: function(element, valueAccessor, bindingContext) { // Do something when the value of the binding changes }, dispose: function(element, valueAccessor, bindingContext) { // Do something when the element is removed from the DOM } };
เพื่อใช้ custom binding ของคุณ คุณต้องกำหนดค่าบอินให้กับองค์ประกอบ DOM โดยใช้ data-bind
Here are some examples of how you can use custom bindings in KnockoutJS:
You can create a custom binding to format a date:
1 2 3 4 5 6 7 8 9 10 11 12 13
ko.bindingHandlers.myBinding = { init: function(element, valueAccessor, bindingContext) { // Do something when the element is created }, update: function(element, valueAccessor, bindingContext) { // Format the date var date = valueAccessor(); element.textContent = moment(date).format('YYYY-MM-DD'); }, dispose: function(element, valueAccessor, bindingContext) { // Do something when the element is removed from the DOM } };
You can create a custom binding to validate a value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
ko.bindingHandlers.myBinding = { init: function(element, valueAccessor, bindingContext) { // Do something when the element is created }, update: function(element, valueAccessor, bindingContext) { // Validate the value var value = valueAccessor(); if (!value.match(/^[0-9]+$/)) { element.setCustomValidity('Value must be a number.'); } else { element.setCustomValidity(''); } }, dispose: function(element, valueAccessor, bindingContext) { // Do something when the element is removed from the DOM } };
You can create a custom binding to create a reusable component:
1 2 3 4 5 6 7 8 9 10 11 12 13
ko.bindingHandlers.myComponent = { init: function(element, valueAccessor, bindingContext) { // Do something when the element is created }, update: function(element, valueAccessor, bindingContext) { // Update the component var component = valueAccessor(); element.textContent = component.render(); }, dispose: function(element, valueAccessor, bindingContext) { // Do something when the element is removed from the DOM } };