3

我有一种情况,我想在 observable 发生变化时执行任务,所以我设置了订阅 - 但是我不希望在创建项目时立即触发。

http://jsfiddle.net/ciel/EeZjH/

基本上,当每个项目从控制器进来时,已经为每个项目设置了“绑定”——所以我还不想发布更改。只有当它们从初始化值改变时。这合理吗?

function Item(data) {
  this.Binding = ko.observable(data);

  this.Binding.subscribe(function (newValue) {
    console.log("The Binding is Now " + newValue);
  });
}

var viewModel = {
  Options: ko.observableArray([{
    "Value": "1",
      "Name": "One"
  }, {
    "Value": "2",
      "Name": "Two"
  }, {
    "Value": "3",
      "Name": "Three"
  }]),
  Items: ko.observableArray([])
};

viewModel.Items.push(new Item("1"));
viewModel.Items.push(new Item("2"));
viewModel.Items.push(new Item("3"));

viewModel.output = ko.computed(function () {
  return JSON.stringify(
  viewModel.Items().map(

  function (i) {
    return i.Binding();
  }));
});

ko.applyBindings(viewModel);
4

1 回答 1

1
ko.observable.fn.beforeAndAfterSubscribe = function (callback, target) {
 var _oldValue;
 this.subscribe(function (oldValue) {
     _oldValue = oldValue;
 }, null, 'beforeChange');
   this.subscribe(function (newValue) {
     callback.call(target, _oldValue, newValue);
 });
}; 
于 2013-03-03T14:46:15.090 回答