Newbie question on clojurescript


#1

Hello,

I want to use clojurescript with the javascript micro-library riotjs:

http://riotjs.com/guide/#example

In a tag file, I have for example the following javascript code:

<script>
    this.disabled = true

    this.items = opts.items

    edit(e) {
      this.text = e.target.value
    }

    add(e) {
      if (this.text) {
        this.items.push({ title: this.text })
        this.text = this.input.value = ''
      }
    }

    toggle(e) {
      var item = e.item
      item.done = !item.done
      return true
    }
  </script>

But I did not find how to compile to the first line : this.disabled = true

Is it possible to get this js code in clojurescript ?

How do “this” in clojurescript ?

Thanks by advance for your help ! :sunny:


#2

Hey there!

Thanks for the question.

It looks like you’re using this in a global context, which in the browser is equivalent to the global window variable. You can access that in ClojureScript with js/window.

If you do need to access this in any context (including the global context), you can use the this-as macro. It lets you bind a new local with the current value of this in the context you’re in.

For example, to do the first two lines of your example:

(this-as this
  (set! (.-disabled this) true)
  (set! (.-items this) (.-items opts)))

The nice thing about the this-as macro is you can name it whatever you want. In JavaScript, this gets rebound so much it’s hard to keep track. In ClojureScript you name it, so you can avoid unnecessary rebindings.

Rock on!
Eric