我需要实现一个复杂的形式。例如,在该总和中存在用于求和的字段,每个求和的总和和百分比。插图:
Value1: 1 10%
Value2: 4 40%
Value3: 5 50%
Sum: 10 100%
现实生活中的例子要复杂得多。一切都是可编辑的。 所以,我假设有几种情况:
我目前正在尝试使用Backbone.js实现类似的功能(仅仅因为我熟悉它),但解决方案看起来已经过度设计了,我刚刚开始。
我想知道,还有其他方法我可以研究一下吗? 我不是一个FRP人,但可能功能/反应方法可以帮助某种程度?
如果有一个旨在解决此类问题的框架或库,我很乐意调查。
答案 0 :(得分:2)
似乎是Constraint编程的任务。我建议您查看https://github.com/slightlyoff/cassowary.js以及此演讲http://www.youtube.com/watch?v=72sWgwaAoyk
答案 1 :(得分:1)
我不久前使用Kefir.js实施了类似的任务。
请找我的例子 - http://jsfiddle.net/mistakster/kwx5j8wm/
主要方法是:
为值,先例和总和创建事件流。
var streamVal = Kefir.fromBinder(function (emitter) {
function handler() {
var values = $.map($table.find('.val'), function (ele) {
return $(ele).val();
});
emitter.emit(values);
}
$table.on('change', '.val', handler);
return function () {
$table.off('change', '.val', handler);
};
});
实施您的业务逻辑,根据流中的数据将更改应用于其他字段。
所以,就是这样。就像画一只猫头鹰一样简单。 : - )
答案 2 :(得分:0)
由于你说其他框架是可以接受的,我在下面创建了一个jQuery解决方案。
标准#3有点含糊不清,如果需要改变,请告诉我:
$('.val').change(function() {
var tot= 0;
$('.val').each(function() {
tot+= parseInt($(this).val(),10);
});
$('#sum').val(tot);
$('.pct').each(function(index) {
$(this).val(($('.val')[index].value/tot*100).toFixed(0));
$(this).data('prevValue', $(this).val());
$(this).data('index', index);
});
});
$('#sum').change(function() {
var sum= $(this).val();
$('.val').each(function(index) {
$(this).val($('.pct')[index].value*sum/100);
});
});
$('.pct').change(function() {
var index= $(this).data('index');
var prevValue= $(this).data('prevValue')
$('.val')[index].value= ($('.val')[index].value*$(this).val()/prevValue).toFixed(0);
$('.val').change();
});
$('.val').change();

.val, .pct, #sum, tpct {
width: 3em;
text-align: right;
}
th {
text-align:right;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>Value1:<td><input class="val" value="1"><td><input class="pct">%
<tr><td>Value2:<td><input class="val" value="4"><td><input class="pct">%
<tr><td>Value3:<td><input class="val" value="5"><td><input class="pct">%
<tr><td>Sum: <td><input id="sum" ><th>100%
</table>
&#13;