2

嵌套组件也预设了嵌套视图模型。

但是,在示例组件中,我没有看到这种依赖关系出现(除了 BackboneJS TODO 应用程序,它对于 KO 用户来说不是很清楚)。

您能否详细说明如何进行这样的设计,例如对于收藏:

  • ItemViewModel具有属性NameIsSelected
  • CollectionViewModelwith 有一个Items属性,它包含一个集合,ItemViewModelSelectedCount是通过计算选择了多少项目来计算的。(我知道这可以用 KO 以更简单的方式完成,但为了说明。
4

2 回答 2

2

Viewmodels(VM)只是对象(使用 绑定ko.applyBindings()) - 这意味着您可以任意将 VM 嵌套到父对象中(@Hasith 所说的)。您只需将一个父对象传递回样板。忍受一些超注释代码:

// Let's assume you have your items nicely formatted in an array 
// data source (and technically the objects in this array can be 
// considered 'dumb' viewmodels)
var items = [
  {Name:'a',isSelected:false}, 
  {Name:'b',isSelected:true}
  ]

// We can apply some bindings to make 'smarter' viewmodels
// One approach is just to map using rocking KO mapping plugin
var koMapItems = ko.mapping.fromJS( items )

// You could skip the mapping plugin and go for broke
// creating your own VM mappings manually
// (you could do this using the mapping plugin with less work)
var goforbrokeVM = function( item )
{
  var _name = ko.observable( item.Name )
  var _dance = function() { return _name+' is space monkey' }

  return {
    Name: _name,
    isSelected: ko.observable( item.isSelected ),
    spaceMonkey: _dance
  }
}
// Don't forget to assign and create your goforbrokeVMs
var epicItemVMs = []
for (var i=0;i<items.length;i++) 
  epicItemVMs.push( new goforbrokeVM( items[i]) )


// Now the interesting part, lets create a 'child' VM that
// we can embed in another VM. Notice this VM has as a
// property an array of VMs itself.
var childVM = {
  elements: epicItemVMs,
  // A sub method, because we can
  otherMethod: function() { return 'wat' }
}

// And ultimately our 'master' VM with its own properties
// including the nested child VM we setup above (which you'll
// remember contains its own sub VMs)
var ParentVM = {
  // And its own property
  parentPropA: ko.observable('whatever'),

  // Oooow look, a list of alternative ko.mapping VMs
  simpleMappedItems: koMapItems,

  // And a nested VM with its own nested goforbrokeVMs
  nested: childVM
}

// Apply your master viewmodel to the appropriate DOM el.
ko.applyBindings( ParentVM, document.getElementById('items'))

还有你的 HTML:

<div id="items">
  <span data-bind="text: parentPropA"></span>

  <!-- Step through one set of items in ParentVM -->
  <div data-bind="foreach: simpleMappedItems">
    <input type="checkbox" data-bind="checked: isSelected">
    <span data-bind="text: Name"></span>
  </div>

  <!-- Or jump into the nested models and go crazy -->
  <!-- ko with: nested -->
    <div data-bind="foreach:elements">
      <div data-bind="text: spaceMonkey"></div>
    </div>
    <div data-bind="text: otherMethod"></div>
  <!-- /ko -->
</div>

通过这种方式,您可以将单个对象(在本例中ParentVM)传递给带有尽可能多的嵌套视图模型的样板。

用于淘汰赛的映射插件信息在这里:http: //knockoutjs.com/documentation/plugins-mapping.html

于 2012-10-04T06:39:57.727 回答
-1

'todo' 示例是通过采用 Addy Osmani 的实现来完成的。这里也有一个 knockoutjs 的实现。

于 2012-09-21T08:58:38.630 回答