Backbone.js: avoid view→model→view double conversion

后端 未结 3 668
庸人自扰
庸人自扰 2021-02-15 17:34

I’m trying to build this:

When I edit field on the left it should update the one on the right and vice-versa.

  • Editing a value in an input field cause

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 17:52

    Two methods come to mind. As Kinakuta mentioned you can do something like the following so you're math works on integers, instead of decimals:

    temp = ((oldTemp * 100) * conversion stuff) / 100
    

    Depending on how complex you want your app to be you can also use something like Backbone.ModelBinder. It automatically binds your view to your model so when one updates, the other updates automatically. You can then attach a converter function to the binding so when your value goes view -> model or model -> view it's run through the converter. I can elaborate more if that idea interests you.

    Update: With a simple temp converter it's not surprising that Backbone requires 3.5x as much code. An MVC framework can reduce bloat in a large project, but for a small app it might be overkill. e.g. imagine using Backbone to display "Hello World".

    As for your issue, how about only rendering the other input value when one is changed, instead of both? If F input changes, re-render value in C box. With ModelBinder I would do this by having two attributes in my model: tempF and tempC. When one is modified, I re-calculate the other and ModelBinder automatically displays it. Or you can go without MB and just listen for the change event.

提交回复
热议问题