如何定义使用先前值来确定Knockout中的类的自定义绑定? [英] How to define a custom binding who use previous value to determine class in Knockout?

查看:80
本文介绍了如何定义使用先前值来确定Knockout中的类的自定义绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用knockout绑定一个表,如果新值高于或低于之前的值,我希望表格单元获得不同的css类。



<我想到了不同的可能性,例如将之前的值存储在bindingContext中并且有一个返回正确类的函数,但是是否可以添加一个自定义绑定处理程序来接收先前的值和新值?

解决方案

虽然 Jeff Sławomir的答案会有效,我找到了一个不需要对其进行任何更改的替代方案。视图模型也不依赖于改变DOM元素对象。

  function subscribeToPreviousValue(observable,fn){
observable.subscribe (fn,this,'beforeChange');
}

ko.bindingHandlers ['bindingWithPrevValue'] = {
init:function(element,valueAccessor){
var observable = valueAccessor();
var current = observable();

console.log('初始值为',当前);

subscribeToPreviousValue(observable,function(previous){
console.log('value from',previous,'to',current);
});
}
};

当然,这只有在绑定属性是可观察的情况下才有效。


I need to bind a table with knockout, and I would like the table cell to get a different css class if the new value is higher or lower of the previous.

I have in mind different possibilities, such as storing the previous value in the bindingContext and have a function which returns the right class, but is it possible to add a custom binding handler which receives the previous value and the new value?

解决方案

Although Jeff's and Sławomir's answers would work, I found an alternative that doesn't need any change to the view model nor relies on altering the DOM element object.

function subscribeToPreviousValue(observable, fn) {
  observable.subscribe(fn, this, 'beforeChange');
}

ko.bindingHandlers['bindingWithPrevValue'] = {
  init: function (element, valueAccessor) {
    var observable = valueAccessor();
    var current = observable();

    console.log('initial value is', current);

    subscribeToPreviousValue(observable, function (previous) {
      console.log('value changed from', previous, 'to', current);
    });
  }
};

Naturally, that will only work if the bound property is an observable.

这篇关于如何定义使用先前值来确定Knockout中的类的自定义绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆