#+TITLE: An attr:href binding
#+SHORT-TITLE: href
#+KEYWORDS: href, compute
#+DESCRIPTION: dynamic hyperlinks
*:max-width=100ex Motivation
Sometimes we need to have a hyperlink with an address bound to the value of a certain dynamic variable (an [[index][observable]]).
For example, suppose you are making a website for an artist: *www.great-artist.com*.
This website has a gallery for each year available on
*www.great-artist.com\/gallery\/YYYY\/*
*:max-width=100ex Example 1
Let us create an [[index][observable]]:
#+BEGIN(src):JavaScript
var addr1=new DB.observable([],{type:"str",
value:"http://www.great-artist.com/gallery/2010/"});
#+END
where =addr1= is a string-valued observable.
On the web page we write:
#+BEGIN(src):HTML
Link to the paintings depicted during the specified year
#+END
Now after our web page loads DB.js and activates it, this link will point to the paintings created in 2010.
*:max-width=100ex Example 2
To complicate the previous example, let us this time create two [[index][observables]]:
#+BEGIN(src):JavaScript
var year2=new DB.observable([],{type:"int",value:2010}),
addr2=new DB.observable([year2],{type:"str",
compute:()=>"http://www.great-artist.com/gallery/"+year2()+"/"});
#+END
where we defined 2 observables:
- integer-valued =year2= with the initial value 2010, and
- string-valued =addr2= derived from =year2=.
Let us use =addr2= to set the link address, and =year2= – to update its text:
#+BEGIN(src):HTML
Link to the paintings created
in
#+END
At this point we could open debugger console in the browser and evaluate
#+BEGIN(src):JavaScript
year2(2011);
#+END
Instead of the debugger console, one can use add =input= element to our web page bound to =year2=:
#+BEGIN(src):HTML
#+END
In this way we have bound =input= element to =a= (http link) via two observables: =year2= and =addr2=.
* Notes
- See also [[ex-href.html]] and [[files/ex-href.js][ex-href.js]] with the above code. In order to test them on your server, place both files together with [[https://github.com/chalaev/DB.js][DB.js]] in
a directory and update the location of [[https://github.com/chalaev/DB.js][DB.js]] in the HTML.