1 | _ = require 'underscore'
|
2 | Hacktiv = require 'hacktiv'
|
3 | N = require '../../'
|
4 |
|
5 | class ChangeWatcher
|
6 |
|
7 | func: null
|
8 | args: null
|
9 | res: {}
|
10 |
|
11 | @list = []
|
12 |
|
13 | (@func, @args, @instance) ->
|
14 | @dep = new Hacktiv.Dependency
|
15 | @doneIdx = @_FindDone()
|
16 |
|
17 | @args[@doneIdx] = @_WrapDoneFirst()
|
18 |
|
19 | _FindDone: ->
|
20 | for arg, i in @args
|
21 | if typeof(arg) is 'function'
|
22 | return i
|
23 |
|
24 | -1
|
25 |
|
26 | _WrapDoneFirst: ->
|
27 | @_oldDone = @args[@doneIdx]
|
28 | @args[@doneIdx] = (err, res) ~>
|
29 | @res = res
|
30 | @_oldDone.call @instance, err, res
|
31 | @_ReWrap()
|
32 |
|
33 | _ReWrap: ->
|
34 | @args[@doneIdx] = (err, res) ~>
|
35 | return if err?
|
36 |
|
37 | if (@res?.length? and res? and @res.length != res.length) or !_(@res).isEqual res
|
38 | @res = res
|
39 | @dep._Changed()
|
40 |
|
41 | Invalidate: ->
|
42 | @dep._Depends()
|
43 | @func.apply @instance, @args
|
44 |
|
45 | @Watch = (func, args, instance) ->
|
46 | return false if not N.Watch.active or _(@list).find (item) -> item.func is func and _(item.args).isEqual args
|
47 |
|
48 | elem = new ChangeWatcher func, args, instance
|
49 | @list.push elem
|
50 | elem.Invalidate()
|
51 |
|
52 | @Invalidate = ->
|
53 | for watcher in @list
|
54 | watcher.Invalidate()
|
55 |
|
56 | module.exports = ChangeWatcher
|