/
DeferredCq.cs
84 lines (68 loc) · 2.04 KB
/
DeferredCq.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
namespace CsQuery.Mvc
{
/// <summary>
/// Encapsulate the deffered creation of the CQ object during processing a view, so it's never created if we don't need it.
/// </summary>
internal class DeferredCq
{
public DeferredCq(Action<ViewContext, TextWriter, object> baseRender, ViewContext viewContext, object instance)
{
ViewContext = viewContext;
CaptureInstanceHtml(baseRender,instance);
}
private ViewContext ViewContext;
private CQ _Dom;
/// <summary>
/// Source HTML of the view.
/// </summary>
public StringBuilder SourceHtml;
/// <summary>
/// Gets the dom, either already built or on demand.
/// </summary>
public CQ Dom
{
get
{
if (_Dom == null)
{
_Dom = GetCqDoc();
}
return _Dom;
}
}
/// <summary>
/// If the instance is going to go out of scope, use this to ensure the deferred object remains
/// valid.
/// </summary>
private void CaptureInstanceHtml(Action<ViewContext, TextWriter, object> baseRender, object instance)
{
if (SourceHtml == null)
{
SourceHtml = new StringBuilder();
var sw = new StringWriter(SourceHtml);
// render the view into out local writer
baseRender(ViewContext, sw, instance);
}
}
/// <summary>
/// When true, the Dom object has been accessed and therefore constructed.
/// </summary>
public bool IsDomCreated
{
get
{
return _Dom != null;
}
}
private CQ GetCqDoc()
{
return CQ.Create(SourceHtml.ToString());
}
}
}