WinJS为我们提供了一些数据绑定的方法来实现MVC和MVVC这种架构,使我们对应用数据的管理和更新变得更加方便
首先,需要创建一个viewmodel,新建一个js文件,并在文件中添加如下代码:
///<reference path="//Microsoft.WinJS.1.0/js/base.js"/> ///<reference path="//Microsoft.WinJS.1.0/js/ui.js"/> (function () { "use strict" WinJS.Namespace.define("ViewModel.UserData", {
_shoppingItems:[],
_preferredStores:[],
homeZipCode: null, getStore: function () { return this._preferredStore; }, addStore: function (newStore) { this._preferredStore.push(newStore); }, getItems: function () { return this._shoppingItems; }, addItems: function (newName, newQuanity, newStore) { this._shoppingItems.push({ item: newName, quanity: newQuanity, store:newStore }); }
}); ViewModel.UserData.homeZipCode = "NY 10086"; ViewModel.UserData.addStore("Yuki"); ViewModel.UserData.addStore ("Nike"); ViewModel.UserData.addItems("Kobe8", 1, "Nike"); })();
这样就定义了一个全局变量,在整个工程里都可以使用,在html文件中添加viewmodel.js的路径:
<script src="viewmodel.js的url"></script>
第一种bindings叫做基本声明绑定,即只能绑定简单变量,类和数组等不能通过这种方法绑定
在html文件中添加一个span,用来显示绑定的内容:
The Zip Code is <span id="zipCode" class="TheZipCode" data-win-bind="innerText:UserData.homeZipCode"></span>
homeZipCode为viewmodel.js文件中所定义的ViewModel.UserData里的一个简单变量
然后再default.js文件的app.onactivated函数里添加如下代码:
app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. performIntialSetup(args); } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); } };
performInitialSetup(e)函数的实现如下:
WinJS.Binding.processAll(document.body, ViewModel);
这样就完成了基本声明绑定,可能大家会有疑问,为什么span的data-win-bind=“UserData.homeZipCode”而不是ViewModel.UserData.homeZipCode,这是因为Declarative data bindings are relative to the data source
可是这种绑定只能显示数据,并不能实现同步更新修改,这时,动态绑定可以帮我们实现
这里需要用到一个函数WinJS.Binding.as(),把ViewModel的成员作为一个object作为WinJS.Binding.as函数的参数,对viewmodel.js文件作以下修改:
WinJS.Namespace.define("ViewModel", { UserData:WinJS.Binding.as({ _shoppingItems:[], _preferredStores:[], homeZipCode: null, getStore: function () { return this._preferredStore; }, addStore: function (newStore) { this._preferredStore.push(newStore); }, getItems: function () { return this._shoppingItems; }, addItems: function (newName, newQuanity, newStore) { this._shoppingItems.push({ item: newName, quanity: newQuanity, store:newStore }); } }), });
在html文件里添加一个输入文本框和一个更新按钮:
.Enter a new zip code:<input id="zipCodeInput" data-win-bind="value:UserData.homeZipCode" /> <button id="update">update</button>
接着,在之前的performInitialSetup(e)函数里添加代码,是在点击更新按钮之后,以输入文本框里的内容重置homeZipCode的值:
WinJS.Utilities.query('#update').listen("click", function (e) { ViewModel.UserData.homeZipCode = WinJS.Utilities.query('#zipCodeInput')[0].value; });
这样在输入一些东西之后,点击更新,就可以看到之前绑定的span的内容也更新为输入的东西
完成了简单变量的绑定,接下来便是一些复杂变量的绑定了,如数组
这时,需要WinJS.Binding.List(),UserData中的两个数组不再是私有成员,必须将其定义为全局变量,在viewmodel.js里做如下修改:
var shoppingItems =new WinJS.Binding.List(); var preferredStore =new WinJS.Binding.List(); WinJS.Namespace.define("ViewModel", { UserData:WinJS.Binding.as({ homeZipCode: null, getStore: function () { return preferredStore; }, addStore: function (newStore) { preferredStore.push(newStore); }, getItems: function () { return shoppingItems; }, addItems: function (newName, newQuanity, newStore) { shoppingItems.push({ item: newName, quanity: newQuanity, store:newStore }); } }), });
在html中添加additem按钮和removeitem按钮还有一个显示最后添加的Item的newName的span:
the last item is:<span id="item"></span> <button id="additem">Add Item</button> <button id="removeitem">Remove Item</button>
在performIntialSetup(e)函数里如入下如下代码:
WinJS.Utilities.query('button').listen("click", function (e) { if (this.id == "additem") { console.log("additem succeed"); ViewModel.UserData.addItems("Kobe9", 1, "Nike"); } else if(this.id=="removeitem") { ViewModel.UserData.getItems().pop(); } }); var setValue = function () { var list = ViewModel.UserData.getItems(); document.getElementById('item').innerText = list.getAt(list.length - 1).item; }; var eventTypes = ["itemchanged", "iteminserted", "itemmoved", "itemremoved"]; eventTypes.forEach(function (type) { ViewModel.UserData.getItems().addEventListener(type, setValue); }); setValue();
eventType的设置是相当重要的,这样,当有新item插入,它才会响应并更新最后插入的item的名字
至此,也完成了数组的绑定