Dependent Methods ใน Kendo MVVM

Chotmanee Thong-aom
Arcadia Software Development
2 min readDec 18, 2018

เวลาที่เราต้องการจะให้ Field ที่อยู่ภายใต้ View-Model มีการเปลี่ยนแปลงค่าไปตามค่าบางอย่าง เพื่อให้สอดคล้องกัน

การสร้าง Dependent Methods

ตัวอย่าง

<span data-bind="text: fullName"></span>
<script>
var viewModel = kendo.observable({
firstName: "Mooking",
lastName: "Potter",
fullName: function(){
return this.get("firstName") + " " + this.get("lastName");
}
});
kendo.bind($("span"), viewModel);
</script>

จากตัวอย่าง เราจะสังเกตได้ว่า มีการประกาศ firstName, lastName เป็น string value และ fullName เป็น function สำหรับดึงข้อมูล fullName ที่นำ firstName กับ lastName มาจัด format ในรูปแบบที่ต้องการ

ในส่วนของ span ได้ถูก bind text จาก fullName ซึ่งหมายความว่า ถ้า firstName หรือ lastName มีการเปลี่ยนแปลงค่าไป ข้อมูลของ fullName จะถูกเปลี่ยนแปลงค่าตามไปด้วย

การกำหนด Values

ตัวอย่าง

<p>Full Name: <input data-bind="value: fullName"></p>
<p>First Name: <span data-bind="text: firstName"></span></p>
<p>Last Name: <span data-bind="text: lastName"></span></p>

<script>
var vm = kendo.observable({
firstName: "Mooking",
lastName: "Potter",
fullName: function(value) {
if (value !== undefined) {
var name = value.split(" ");

this.set("firstName", name[0]);
this.set("lastName", name[1]);
} else {
return this.get("firstName") + " " + this.get("lastName");
}
}
});
kendo.bind(document.body, vm);
</script>

จากตัวอย่าง เมื่อมีการรับค่าจาก input ของ fullName จะถูกนำไป set values ใหักับ firstName และ lastName

ข้อควรระวัง

เมื่อมีการทำ function สำหรับคำนวณ values ควรคำนึงถึง values ที่ได้รับมา และที่จะเกิดขึ้นด้วย

ตัวอย่างที่ไม่ควรทำ

var viewModel = kendo.observable({
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
});

ให้สังเกตที่ fullName function การที่เราเข้าถึง firstName และ lastName โดยตรง fullName จะไม่ถูกเปลี่ยนแปลงค่า เมื่อมีการ เมื่อมีการ set values ให้กับ firstName และ lastName โดยใช้ set methods

ตัวอย่างที่ควรทำ

var viewModel = kendo.observable({
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.get("firstName") + " " + this.get("lastName");
}
});

สรุป

การทำ dependent methods จะต้องทำภายใต้ get method ของ Kendo MVVM ให้หลีกเลี่ยงการเข้าถึง values โดยตรง เมื่อต้องการให้ field มีการ dependent กัน

--

--