现在支持数据绑定的现代组件是 angular、aurelia 和 react(有点……+redux 快要死了)。jQuery 没有提供好的数据绑定实现。它需要手动连接所有道具更改。可能实现一些观察者/订阅者方法。
或者使用一些提供足够方便的数据绑定定义命令的数据绑定任务的组件。我用databindjs做到了。例如
// Lets assume that there is just simple form (target)
var simpleForm = {
input: $('.simple .input-value'),
output: $('.simple .output-value')
};
// And here is the simple model object (source)
var model = {
text: 'initial value'
};
// Lets set two directional binding between [input] <-> [text]
var simpleBinding = bindTo(simpleForm, () => model, {
'input.val': 'text', // bind to user input
'output.text': 'text' // simple region that will react on user input
});
// This command will sync values from source to target (from model to view)
updateLayout(simpleBinding);
subscribeToChange(simpleBinding, () => {
$('.simple .console').html(JSON.stringify(model));
});
// Just initialize console from default model state
$('.simple .console').html(JSON.stringify(model));
完整的解决方案在这里