2017-05-09 13 views
0

私は単純な時間入力フォームを持って、ここを参照してください:https://codepen.io/dikuw/pen/rmpozm動的データをオブジェクトに保存しますか?

を私はユーザーとして動的に時刻データを保存するには、追加、変更、および行を削除し、オブジェクトを考えています最良の方法です。

私の質問はベストプラクティスですか?コンストラクタを作成する必要がありますか?

function TimesheetRecord(id, TSDate, TSStaffId, Hours, Comments, TSTaskId, Billable) { 
    this.id = id; 
    this.TSDate = TSDate; 
    this.TSStaffId = TSStaffId; 
    this.Hours = Hours; 
    this.Comments = Comments; 
    this.TSTaskId = TSTaskId; 
    this.Billable = Billable; 
} 

ユーザーが行を追加するたびに新しいオブジェクトを動的に作成しますか?私がそれをすれば、そこにどれくらいの物があるのか​​、どうすればわかるでしょうか?

+1

単純なオブジェクト '{'key':value}'を作るためには、表記法がずっと簡単で速くなります。 –

+1

オブジェクトを格納して内部の要素を数えるには 'set'または' array'を使います。 – Slime

+1

それらを配列に入れますか? –

答えて

1

ここでは、すべてのタイムシートレコードを格納する配列を作成し、新しいタイムテーブルレコードを作成するときに新しい動的オブジェクトをプッシュできます。

// When app starts (dataFromDB is data fetched from db if any) 
const TimesheetRecords = dataFromDB || [] 

// create a new record(mainly in a function) 
const TimesheetRecord = { 
    id: id, 
    TSDate: TSDate, 
    TSStaffId: TSStaffId, 
    Hours: Hours, 
    Comments: Comments, 
    TSTaskId: TSTaskId, 
    Billable: Billable 
} 

// store to db (ajax) and then push to array 
TimesheetRecords.push(TimesheetRecord) 

// Check how many records are there 
const count = TimesheetRecords.length 

これは、JavaScriptで動作(メソッド)を使用しない単純なオブジェクトを格納するための一般的なパターンです。

関連する問題