Skip to content

Commit dad51be

Browse files
committed
update document for recursive view
1 parent f843894 commit dad51be

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

README.md

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -278,16 +278,27 @@ When handlers for each ld node is called, it contains following parameters:
278278

279279
It's possible to define view recursively - simply refer a view config in itself:
280280

281-
(cfg = {}) <<< handler: someDirective: {
281+
cfg = {}
282+
cfg <<< handler: someDirective: {
282283
list: -> ...
283284
view: cfg
284285
}
285286

286-
However, this requires a recursively defined DOM, which is only possible with `template` option:
287+
Please note that the first `cfg = {}` is necessary since cfg won't be available for recursive definition when we initialize it, such as:
288+
289+
cfg = handler: someDirective: {
290+
list: -> ...
291+
# incorrect: cfg is not available here.
292+
view: cfg
293+
}
294+
295+
296+
Additionally, we need also a recursively defined DOM, which is only possible with `template` option:
287297

288298
div(data-name="template"): ...
289299
script(type="text/livescript").
290-
new ldview (cfg = {}) <<< {
300+
cfg = {}
301+
new ldview cfg <<< {
291302
template: document.querySelector('[data-name=template]')
292303
handler: someDirective: {
293304
list: ({ctx}) -> ...
@@ -299,10 +310,32 @@ In this case, the div named `template` will be cloned, attached and used as inne
299310

300311
Also please note that `ctx` should not be defined in the reused `cfg`, otherwise it may cause infinite recursive calls, leading to maximal callstack exceeded exception. Following is a correct example:
301312

302-
{ctx: mydata} <<< (cfg = {}) <<< {
313+
cfg = {}
314+
{ctx: mydata} <<< cfg <<< {
303315
handler: myselector: view: cfg
304316
}
305317

318+
A workable, complete example with both JS and HTML (written in Pug) is as below:
319+
320+
//- HTML
321+
.template #[div(ld="title")]#[div(ld-each="child")]
322+
#root
323+
324+
# JS - DATA
325+
ctx = name: "root", list: [
326+
* name: "entry1", list: [{name: "sub entry 1.1"}]
327+
* name: "entry2", list: [{name: "sub entry 2.1"}, {name: "sub entry 2.2"}]
328+
* name: "entry3", list: [{name: "sub entry 3.1"}, {name: "sub entry 3.2"}]
329+
]
330+
# JS - View Code
331+
cfg = {}
332+
cfg <<<
333+
text: title: ({ctx}) -> ctx.name
334+
handler: child:
335+
view: cfg
336+
list: ({ctx}) -> ctx.list or []
337+
view = new ldview({root: root, ctx: -> list} <<< cfg)
338+
306339

307340
## Nested Local Views and Template
308341

0 commit comments

Comments
 (0)