加载中...

第九章:高级应用举例


1   Contacts editor

这个例子和微软为演示jQuery Data Linking Proposal例子提供的例子一样的提供的,我们可以看看Knockout实现是难了还是容易了。

代码量的多少不重要(尽快Knockout 的实现很简洁),重要的看起来是否容易理解且可读。查看HTML源代码,看看如何实现的view model以及绑定的。

 

代码: View

  1. <h2>Contacts</h2>
  2. <div id="contactsList" data-bind='template: "contactsListTemplate"'>
  3. </div>
  4. <script type="text/html" id="contactsListTemplate">
  5. <table class='contactsEditor'>
  6. <tr>
  7. <th>First name</th>
  8. <th>Last name</th>
  9. <th>Phone numbers</th>
  10. </tr>
  11. {{each(i, contact) contacts()}}
  12. <tr>
  13. <td>
  14. <input data-bind="value: firstName"/>
  15. <div><a href="#" data-bind="click: function() { viewModel.removeContact(contact) }">Delete</a></div>
  16. </td>
  17. <td><input data-bind="value: lastName"/></td>
  18. <td>
  19. <table>
  20. {{each(i, phone) phones}}
  21. <tr>
  22. <td><input data-bind="value: type"/></td>
  23. <td><input data-bind="value: number"/></td>
  24. <td><a href="#" data-bind="click: function() { viewModel.removePhone(contact, phone) }">Delete</a></td>
  25. </tr>
  26. {{/each}}
  27. </table>
  28. <a href="#" data-bind="click: function() { viewModel.addPhone(contact) }">Add number</a>
  29. </td>
  30. </tr>
  31. {{/each}}
  32. </table>
  33. </script>
  34. <p>
  35. <button data-bind="click: addContact">
  36. Add a contact</button>
  37. <button data-bind="click: save, enable: contacts().length > 0">
  38. Save to JSON</button>
  39. </p>
  40. <textarea data-bind="value: lastSavedJson" rows="5" cols="60" disabled="disabled"> </textarea>

代码: View model

  1. var viewModel = {
  2. contacts: new ko.observableArray([
  3. { firstName: "Danny", lastName: "LaRusso", phones: [
  4. { type: "Mobile", number: "(555) 121-2121" },
  5. { type: "Home", number: "(555) 123-4567"}]
  6. },
  7. { firstName: "Sensei", lastName: "Miyagi", phones: [
  8. { type: "Mobile", number: "(555) 444-2222" },
  9. { type: "Home", number: "(555) 999-1212"}]
  10. }
  11. ]),
  12. addContact: function () {
  13. viewModel.contacts.push({ firstName: "", lastName: "", phones: [] });
  14. },
  15. removeContact: function (contact) {
  16. viewModel.contacts.remove(contact);
  17. },
  18. addPhone: function (contact) {
  19. contact.phones.push({ type: "", number: "" });
  20. viewModel.contacts.valueHasMutated();
  21. },
  22. removePhone: function (contact, phone) {
  23. ko.utils.arrayRemoveItem(contact.phones, phone);
  24. viewModel.contacts.valueHasMutated();
  25. },
  26. save: function () {
  27. viewModel.lastSavedJson(JSON.stringify(viewModel.contacts(), null, 2));
  28. },
  29. lastSavedJson: new ko.observable("")
  30. };
  31. ko.applyBindings(viewModel);

2   Editable grid

该例是使用“foreach”绑定为数组里的每一项来render到 template上。好处(相对于模板内部使用for循环)是当你添加或者删除item项的时候,Knockout不需要重新render – 只需要render新的item项。就是说UI上其它控件的状态(比如验证状态)不会丢失。

如何一步一步构建这个例子并集成ASP.NET MVC,请参阅此贴

 

代码: View

  1. <form action="/someServerSideHandler">
  2. <p>
  3. You have asked for <span data-bind="text: gifts().length">&nbsp;</span> gift(s)</p>
  4. <table data-bind="visible: gifts().length > 0">
  5. <thead>
  6. <tr>
  7. <th>Gift name</th>
  8. <th>Price</th>
  9. <th></th>
  10. </tr>
  11. </thead>
  12. <tbody data-bind='template: { name: "giftRowTemplate", foreach: gifts }'>
  13. </tbody>
  14. </table>
  15. <button data-bind="click: addGift">
  16. Add Gift</button>
  17. <button data-bind="enable: gifts().length > 0" type="submit">
  18. Submit</button>
  19. </form>
  20. <script type="text/html" id="giftRowTemplate">
  21. <tr>
  22. <td><input data-bind="value: name, uniqueName: true"/></td>
  23. <td><input data-bind="value: price, uniqueName: true"/></td>
  24. <td><a href="#" data-bind="click: function() { viewModel.removeGift($data) }">Delete</a></td>
  25. </tr>
  26. </script>

代码: View model

  1. var viewModel = {
  2. gifts: ko.observableArray([
  3. { name: "Tall Hat", price: "39.95" },
  4. { name: "Long Cloak", price: "120.00" }
  5. ]),
  6. addGift: function () {
  7. this.gifts.push({ name: "", price: "" });
  8. },
  9. removeGift: function (gift) {
  10. this.gifts.remove(gift);
  11. },
  12. save: function (form) {
  13. alert("Could now transmit to server: " + ko.utils.stringifyJson(this.gifts));
  14. // To transmit to server, write this: ko.utils.postJson($("form")[0], this.gifts);
  15. }
  16. };
  17. ko.applyBindings(viewModel);
  18. $("form").validate({ submitHandler: function () { viewModel.save() } });

3   Shopping cart screen

这个例子展示的是依赖监控属性(dependent observable)怎么样链在一起。每个cart对象都有一个dependentObservable对象去计算自己的subtotal,这些又被一个进一步的dependentObservable对象依赖计算总的价格。当改变数据的时候,整个链上的依赖监控属性都会改变,所有相关的UI元素也会被更新。

这个例子也展示了如何创建联动的下拉菜单。

代码: View

  1. <div id="cartEditor">
  2. <table width="100%">
  3. <thead>
  4. <tr>
  5. <th width="25%">Category</th>
  6. <th width="25%">Product</th>
  7. <th width="15%" class='price'>Price</th>
  8. <th width="10%" class='quantity'>Quantity</th>
  9. <th width="15%" class='price'>Subtotal</th>
  10. <th width="10%"></th>
  11. </tr>
  12. </thead>
  13. <tbody data-bind='template: {name: "cartRowTemplate", foreach: lines}'>
  14. </tbody>
  15. </table>
  16. <p>
  17. Total value: <span data-bind="text: formatCurrency(grandTotal())"></span>
  18. </p>
  19. <button data-bind="click: addLine">
  20. Add product</button>
  21. <button data-bind="click: save">
  22. Submit order</button>
  23. </div>
  24. <script type="text/html" id="cartRowTemplate">
  25. <tr>
  26. <td><select data-bind='options: sampleProductCategories, optionsText: "name", optionsCaption: "Select...", value: category'></select></td>
  27. <td><select data-bind='visible: category, options: category() ? category().products : null, optionsText: "name", optionsCaption: "Select...", value: product'></select></td>
  28. <td class='price'><span data-bind='text: product() ? formatCurrency(product().price) : ""'></span></td>
  29. <td class='quantity'><input data-bind='visible: product, value: quantity, valueUpdate: "afterkeydown"'/></td>
  30. <td class='price'><span data-bind='visible: product, text: formatCurrency(subtotal())'></span></td>
  31. <td><a href="#" data-bind='click: function() { cartViewModel.removeLine($data) }'>Remove</a></td>
  32. </tr>
  33. </script>

代码: View model

  1. function formatCurrency(value) { return "$" + value.toFixed(2); }
  2. var cartLine = function () {
  3. this.category = ko.observable();
  4. this.product = ko.observable();
  5. this.quantity = ko.observable(1);
  6. this.subtotal = ko.dependentObservable(function () {
  7. return this.product() ? this.product().price * parseInt("0" + this.quantity(), 10) : 0;
  8. } .bind(this));
  9. // Whenever the category changes, reset the product selection
  10. this.category.subscribe(function () { this.product(undefined); } .bind(this));
  11. };
  12. var cart = function () {
  13. // Stores an array of lines, and from these, can work out the grandTotal
  14. this.lines = ko.observableArray([new cartLine()]); // Put one line in by default
  15. this.grandTotal = ko.dependentObservable(function () {
  16. var total = 0;
  17. for (var i = 0; i < this.lines().length; i++)
  18. total += this.lines()[i].subtotal();
  19. return total;
  20. } .bind(this));
  21. // Operations
  22. this.addLine = function () { this.lines.push(new cartLine()) };
  23. this.removeLine = function (line) { this.lines.remove(line) };
  24. this.save = function () {
  25. var dataToSave = $.map(this.lines(), function (line) {
  26. return line.product() ? { productName: line.product().name, quantity: line.quantity()} : undefined
  27. });
  28. alert("Could now send this to server: " + JSON.stringify(dataToSave));
  29. };
  30. };
  31. var cartViewModel = new cart();
  32. ko.applyBindings(cartViewModel, document.getElementById("cartEditor"));

4   Twitter client

这是一个复杂的例子,展示了几乎所有Knockout特性来构建一个富客户端。

用户数据存在一个JavaScript模型里,通过模板来展示。就是说我们可以通过清理用户列表里的数据来达到隐藏用户信息的目的,而不需要手动去隐藏DOM元素。

按钮将根据他们是否可操作来自动变成enabled或disabled状态。例如,有一个叫hasUnsavedChanges的依赖监控属性(dependentObservable)控制这“Save”按钮的enabled状态。

可以非常方便地从外部JSON服务获取数据,并集成到view model里,然后显示在页面上。

代码: View

  1. <div>
  2. Loading...</div>
  3. <div>
  4. <div>
  5. <button data-bind='click: deleteList, enable: editingList.name'>
  6. Delete</button>
  7. <button data-bind='click: saveChanges, enable: hasUnsavedChanges'>
  8. Save</button>
  9. <select data-bind='options: savedLists, optionsValue: "name", value: editingList.name'>
  10. </select>
  11. </div>
  12. <p>
  13. Currently viewing <span data-bind="text: editingList.userNames().length">&nbsp;</span>
  14. user(s):</p>
  15. <div data-bind='template: { name: "usersTemplate", data: editingList }'>
  16. </div>
  17. <form data-bind="submit: addUser">
  18. <label>
  19. Add user:</label>
  20. <input data-bind='value: userNameToAdd, valueUpdate: "keyup", css: { invalid: !userNameToAddIsValid() }' />
  21. <button type="submit" data-bind='enable: userNameToAddIsValid() && userNameToAdd() != ""'>
  22. Add</button>
  23. </form>
  24. </div>
  25. <div data-bind='template: { name: "tweetsTemplate", data: currentTweets }'>
  26. </div>
  27. <script type="text/html" id="tweetsTemplate">
  28. <table width="100%">
  29. {{each $data}}
  30. <tr>
  31. <td><img src="${ profile_image_url }"/></td>
  32. <td>
  33. <a href="http://twitter.com/${ from_user }">${ from_user }</a>
  34. ${ text }
  35. <div>${ created_at }</div>
  36. </td>
  37. </tr>
  38. {{/each}}
  39. </table>
  40. </script>
  41. <script type="text/html" id="usersTemplate">
  42. <ul>
  43. {{each(i, userName) userNames()}}
  44. <li><button data-bind="click: function() { userNames.remove(userName) }">Remove</button> <div>${ userName }</div></li>
  45. {{/each}}
  46. </ul>
  47. </script>

代码: View model

  1. // The view model holds all the state we're working with. It also has methods that can edit it, and it uses
  2. // dependentObservables to compute more state in terms of the underlying data
  3. // --
  4. // The view (i.e., the HTML UI) binds to this using data-bind attributes, so it always stays up-to-date with
  5. // the view model, even though the view model does not know or care about any view that binds to it
  6. var viewModel = {
  7. savedLists: ko.observableArray([
  8. { name: "Celebrities", userNames: ['JohnCleese', 'MCHammer', 'StephenFry', 'algore', 'StevenSanderson'] },
  9. { name: "Microsoft people", userNames: ['BillGates', 'shanselman', 'haacked', 'ScottGu'] },
  10. { name: "Tech pundits", userNames: ['Scobleizer', 'LeoLaporte', 'techcrunch', 'BoingBoing', 'timoreilly', 'codinghorror'] }
  11. ]),
  12. editingList: {
  13. name: ko.observable("Tech pundits"),
  14. userNames: ko.observableArray()
  15. },
  16. userNameToAdd: ko.observable(""),
  17. currentTweets: ko.observableArray([])
  18. };
  19. viewModel.findSavedList = function (name) {
  20. var lists = this.savedLists();
  21. for (var i = 0; i < lists.length; i++)
  22. if (lists[i].name === name)
  23. return lists[i];
  24. };
  25. // Methods
  26. viewModel.addUser = function () {
  27. if (this.userNameToAdd() && this.userNameToAddIsValid()) {
  28. this.editingList.userNames.push(this.userNameToAdd());
  29. this.userNameToAdd("");
  30. }
  31. }
  32. viewModel.saveChanges = function () {
  33. var saveAs = prompt("Save as", this.editingList.name());
  34. if (saveAs) {
  35. var dataToSave = this.editingList.userNames().slice(0);
  36. var existingSavedList = this.findSavedList(saveAs);
  37. if (existingSavedList)
  38. existingSavedList.userNames = dataToSave; // Overwrite existing list
  39. else
  40. this.savedLists.push({ name: saveAs, userNames: dataToSave }); // Add new list
  41. this.editingList.name(saveAs);
  42. }
  43. }
  44. viewModel.deleteList = function () {
  45. var nameToDelete = this.editingList.name();
  46. var savedListsExceptOneToDelete = $.grep(this.savedLists(), function (list) { return list.name != nameToDelete });
  47. this.editingList.name(savedListsExceptOneToDelete.length == 0 ? null : savedListsExceptOneToDelete[0].name);
  48. this.savedLists(savedListsExceptOneToDelete);
  49. };
  50. ko.dependentObservable(function () {
  51. // Observe viewModel.editingList.name(), so when it changes (i.e., user selects a different list) we know to copy the saved list into the editing list
  52. var savedList = viewModel.findSavedList(viewModel.editingList.name());
  53. if (savedList) {
  54. var userNamesCopy = savedList.userNames.slice(0);
  55. viewModel.editingList.userNames(userNamesCopy);
  56. } else
  57. viewModel.editingList.userNames([]);
  58. });
  59. viewModel.hasUnsavedChanges = ko.dependentObservable(function () {
  60. if (!this.editingList.name())
  61. return this.editingList.userNames().length > 0;
  62. var savedData = this.findSavedList(this.editingList.name()).userNames;
  63. var editingData = this.editingList.userNames();
  64. return savedData.join("|") != editingData.join("|");
  65. }, viewModel);
  66. viewModel.userNameToAddIsValid = ko.dependentObservable(function () {
  67. return (this.userNameToAdd() == "") || (this.userNameToAdd().match(/^\s*[a-zA-Z0-9_]{1,15}\s*$/) != null);
  68. }, viewModel);
  69. // The active user tweets are (asynchronously) computed from editingList.userNames
  70. ko.dependentObservable(function () {
  71. twitterApi.getTweetsForUsers(this.editingList.userNames(), function (data) { viewModel.currentTweets(data) })
  72. }, viewModel);
  73. ko.applyBindings(viewModel);
  74. // Using jQuery for Ajax loading indicator - nothing to do with Knockout
  75. $(".loadingIndicator").ajaxStart(function () { $(this).fadeIn(); })
  76. .ajaxComplete(function () { $(this).fadeOut(); });

还没有评论.