1
+ var AppDispatcher = require ( 'dispatcher' ) ;
2
+ var AppConstant = require ( 'app-constants' ) ;
3
+ var assign = require ( 'object-assign' ) ;
4
+
5
+ var EeventEmitter = require ( 'events' ) . EventEmitter ;
6
+
7
+ var CHANGE_EVENT = "change" ;
8
+ var _catalog = [ ] ;
9
+
10
+ for ( var i = 1 ; i < 5 ; i ++ ) {
11
+ _catalog . push ( {
12
+ 'id' : 'cart' + i ,
13
+ 'title' : 'Title Product' ,
14
+ 'details' : 'Title Product' ,
15
+ 'description' : 'Title Product' ,
16
+ 'cost' : i
17
+ } )
18
+ }
19
+ var _cartItem = [ ] ;
20
+ fucntion _addItem ( item ) {
21
+ if ( ! item . inCart ) {
22
+ item [ 'qty' ] = 1 ;
23
+ item [ 'inCart' ] = true ;
24
+ _cartItem . push ( item ) ;
25
+ }
26
+ else {
27
+ _cartItem . forEach ( function ( cartItem , index ) {
28
+ if ( cartItem . index == item . id ) {
29
+ __incItem ( index ) ;
30
+ }
31
+ } ) ;
32
+ }
33
+ }
34
+ function _removeItem ( index ) {
35
+ _cartItem [ index ] . inCart = false ;
36
+ _cartItem . splice ( index , 1 ) ;
37
+ }
38
+ function _incItem ( index ) {
39
+ _cartItem [ index ] . qty ++ ;
40
+ }
41
+ function _decItem ( index ) {
42
+ if ( _cartItem [ index ] . qty > 1 ) {
43
+ _cartItem [ index ] . qty -- ;
44
+ }
45
+ else {
46
+ _removeItem ( index ) ;
47
+ }
48
+ }
49
+ function _cartTotal ( ) {
50
+ var qty = 0 , total = 0 ;
51
+ _cartItem . array . forEach ( function ( cartItem ) {
52
+ qty += cartItem . qty ;
53
+ total += cartItem . qty * cartItem . cost ;
54
+ } ) ;
55
+ return { 'qty' : qty , 'total' : total }
56
+ }
57
+ AppDispatcher . register ( function ( payload ) {
58
+ var action = payload . actionType ;
59
+ switch ( action ) {
60
+ case AppConstant . ADD_ITEM :
61
+ _addItem ( item )
62
+ //emit change-event and notify app
63
+ break ;
64
+ case AppConstant . REMOVE_ITEM :
65
+ _removeItem ( payload . index )
66
+ break ;
67
+ case AppConstant . INC_ITEM :
68
+ _incItem ( payload . index )
69
+ break ;
70
+ case AppConstant . DEC_ITEM :
71
+ _decItem ( payload . index )
72
+ break ;
73
+ default :
74
+ }
75
+ } )
76
+
77
+ Var AppStore = assign ( EventEmitter . prototype , {
78
+
79
+ emitChnage : function ( ) {
80
+ this . emitChange ( CHANGE_CHANGE )
81
+ } ,
82
+ addChangeListener : function ( callabck ) {
83
+ this . on ( CHANGE_EVENT , callback )
84
+ } ,
85
+ getCart : function ( ) {
86
+ return _cartItem ;
87
+ } ,
88
+ getCatalog : function ( ) {
89
+ return _catalog ;
90
+ } ,
91
+ getCartTotal : function ( ) {
92
+ return _cartTotal ( ) ;
93
+ }
94
+
95
+ } )
0 commit comments