是否可以在单击函数中传递特定模型?

时间:2015-11-04 14:08:42

标签: javascript knockout.js

我很难确定如何在函数中传递指定的url1 <- sub('\\/\\w+$', '', urls) tapply(urls, match(url1, domains), FUN= sample, 1) (比如model函数)。

我有这个模型。

的javascript

click

HTML

var Bar = function() {
  this.id = ko.observable();
  this.name = ko.observable();
  this.barItems = ko.observableArray([]);
};

var BarItem = function() {
  this.id = ko.observable();
  this.type = ko.observable();
};

var addBarItem = function(item) {
  // seems that the "item" here is the whole viewmodel
};

var bars = ko.observableArray([]); // the elements here are Bar objects
var selectedBar = ko.observable(); // passed a Bar object

点击添加栏项后,它会获得<div data-bind="with: selectedBar"> <p data-bind="text: name></p> <div> <input type="text" data-bind="value: type" /> <button data-bind="click: $root.addBarItem">Add Bar Item</button> </div> </div> 个对象。我如何通过那里的Bar

非常感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:1)

将您需要的任何内容集成到您的viewmodel中。以此为出发点。

var BarViewModel = function() {
    var self = this;

    self.Bar = {
      id: ko.observable(),
      name: ko.observable(),
      barItems: ko.observableArray([])
    };

    self.BarItem = {
      id: ko.observable(),
      type: ko.observable()
    };

    self.addBarItem = function(item) {
      // when referenced within foreach will receive the current item automatically
    };

    self.bars = ko.observableArray([]); // the elements here will be Bar objects
    self.selectedBar = ko.observable(); // passed a Bar object
};

ko.applyBindings(new BarViewModel());