2013-04-23 75 views
5

我有一个包含大量变量的工作视图模型。Knockout.js修改ko.observable()之前的值写入

我在文本框中使用autoNumeric(http://www.decorplanit.com/plugin/)进行文本格式设置。我想在计算的可观察值中使用输入字段的观察数据,但如果格式化的可观察文本字段被修改,格式也会保存在变量中。

我怎样才能只观察没有格式化输入字段的值?

我认为这最好的方法可能是一个getter/setter到observable,并在设置值时删除格式。我找不到在knockout的文档中为ko.observable()编写get/set方法的解决方案,而ko.computed()不能存储值。

我不想使用隐藏字段或额外的变量。
没有它,这可能吗?

回答

3

解决方案,在http://knockoutjs.com/documentation/extenders.html

ko.extenders.numeric = function(target, precision) { 
//create a writeable computed observable to intercept writes to our observable 
var result = ko.computed({ 
    read: target, //always return the original observables value 
    write: function(newValue) { 
     var current = target(), 
      roundingMultiplier = Math.pow(10, precision), 
      newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue), 
      valueToWrite = Math.round(newValueAsNum * roundingMultiplier)/roundingMultiplier; 

     //only write if it changed 
     if (valueToWrite !== current) { 
      target(valueToWrite); 
     } else { 
      //if the rounded value is the same, but a different value was written, force a notification for the current field 
      if (newValue !== current) { 
       target.notifySubscribers(valueToWrite); 
      } 
     } 
    } 
}); 

//initialize with current value to make sure it is rounded appropriately 
result(target()); 

//return the new computed observable 
return result; 
}; 

所看到后来就

function AppViewModel(one, two) { 
    this.myNumberOne = ko.observable(one).extend({ numeric: 0 }); 
    this.myNumberTwo = ko.observable(two).extend({ numeric: 2 }); 
} 
+0

这也会创建一个额外的变量('result = ko.computed(...)') – mhu 2013-10-10 22:20:17

+0

,但不在视图模型中。 – zeal 2013-10-12 22:35:06

1

您可以使用ko.computed()。你可以指定一个写选项,看到Writeable computed observables

例(从淘汰赛资料为准):

function MyViewModel() { 
    this.price = ko.observable(25.99); 

    this.formattedPrice = ko.computed({ 
     read: function() { 
      return '$' + this.price().toFixed(2); 
     }, 
     write: function (value) { 
      // Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable 
      value = parseFloat(value.replace(/[^\.\d]/g, "")); 
      this.price(isNaN(value) ? 0 : value); // Write to underlying storage 
     }, 
     owner: this 
    }); 
} 

ko.applyBindings(new MyViewModel()); 
+0

正如我所说“ko.computed()无法存储值” – zeal 2013-04-23 14:34:43

+0

我想要av oid也创建了更多变量。不是答案。 – zeal 2013-04-23 14:35:25

+0

但是,如果您使用写入选项,您可以**存储值。您是否查看过文档? – mhu 2013-04-23 14:39:37

相关问题