3

モデルのsetまたはメソッドを呼び出すときに、データをどのように変換するのか疑問に思いました。save具体的には、入力された日付文字列をエポックタイムに変換します。

ビューで変換できることはわかっていますが、私が知る限り、それは私の検証ではうまく機能しません。

興味のある方はモデルコードはこちらです。

助けてくれてありがとう!

4

3 に答える 3

3

私が収集できるものには、次の 2 つのオプションがあります。

1 ビューでそれらを変換する

これは、ビューに対して独自の変換を行うか、Backbone.modelbinder などを使用して変換を行うことができることを意味します。次に、エポック日付を受け入れるように検証メソッドを変更する必要があります。個人的にはこちらの方が好みです。UI がユーザー入力の整形式の検証と適切な単位への変換を処理し、値が許容範囲内にあるかどうかの検証をモデルに処理させるのに適していると思います。

2 モデルでそれらを変換する

バックボーンは、これをすぐに使用できるものではありません。何かを何かに設定した場合、特に と の間validateで、それを別のものに変換する簡単な方法はありませんset。基本的に、あなたの最善の策は、独自の関数を次のようにロールsetバックすることです

// Inside the set function
...
if (!this._validate(attrs, options)) return false; // real line in the set func
// insert something like this, after validate you know the values are eligible for conversion
attrs = this.convert(attrs); // a custom func that converts attributes to right units
...
// set continues as usual

お役に立てれば!

于 2012-08-15T08:15:21.053 に答える
-1

According to the sources, validate is the only callback that is called before set and save. You can to set the values in your validate method directly on the attributes object. Unfortunately you cannot make any changes to attributes at this point.

You can use a plugin like backbone.getters.setters to do this since it looks like it won't be a feature added to backbone.

于 2012-08-15T07:52:54.917 に答える