avalon0.8一个最大目标是实现对数组的深层监控,可是面临的困难重重,至今还没有什么起色。于是看一下其他两个MVVM框架的做法(knockout, emberjs, angular都不能监听家庭数组元素的属性改动)
WinJS.Binding.List的详细文档可见这里
我写了一些测试示例,发现它是生成一个新对象来处理,而且不是数组实例,也不是类数组对象,用起点有点别扭。
var object = new WinJS.Binding.List([1, 2, 3, 5, {a: 4}]); console.log(object) console.log(object.getItem(0)) console.log(object.getAt(0)) object.addEventListener("iteminserted", function() { console.log(arguments) }) object.addEventListener("itemchanged", function() { console.log(arguments) }) object.addEventListener("itemmutated", function() { console.log(arguments) }) object.push(7, 8, 9) object.setAt(0, 10) object.setAt(4, {a: 7}) console.log(object.getItem(4)) object.getItem(4).data.a = "7777777" object.notifyMutated(4)
kendo ui的监控数组可见这里这里
var array = new kendo.data.ObservableArray([1, 2, 3]); array.bind("change", function(e) { console.log(e.action, e.index, e.items); }); array.push(4, 5); // outputs "add", 3, [4, 5] array.pop(); // outputs "remove", 4, [5] var people = new kendo.data.ObservableArray([{ name: "John Doe" }]); people.bind("change", function(e) { console.log(e.action, e.field, e.items[0].get("name")); }); people[0].set("name", "Jane Doe"); // outputs "itemchange", "name", "Jane Doe"
从它们的接口设计来看,它们不像avalon原打算的那样,通过监控数组所在的VM来监控,而是监控数组本来就应该自己管好自己。
avalon.define("xxx", function(vm){ vm.array = [1,2,3,4] vm.$watch("array.length", callback) }) //打算从上面的接口换成下面这种 var model = avalon.define("xxx", function(vm){ vm.array = [1,2,3,4] }) model.$watch("length", callback) model.$watch("remove", callback) model.$watch("add", callback) model.$watch("change", callback)