2

这是用于 Knockout 的 JS 示例:

function AppViewModel() {
    this.firstName = ko.observable('Bob');
    this.lastName = ko.observable('Smith');
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
}

如果您不熟悉 KO,则每个字段AppViewModel都将成为一个函数(即ko.observable,每个字段ko.computed都返回一个函数。还要注意这fullName取决于两个函数。

如何将其重写为 ClojureScript?

要尝试的一件事是:

(deftype AppViewModel [firstName lastName]
  Object
  (fullName [this] (.computed js/ko (str (firstName) " " (lastName)))))

(defn my-model [first last]
  (AppViewModel. 
    (.observable js/ko "Bob") 
    (.observable js/ko "Smith")))

但它不起作用,因为它fullName变成了一个调用ko.computed. 也就是说,它编译为:

my_namespace.AppViewModel.prototype.fullName = function() {
  return ko.computed([cljs.core.str(this.firstName.call(null)), cljs.core.str(" "), cljs.core.str(this.lastName.call(null))].join(""))
};

如何在 ClojureScript 中处理它?

再次注意fullNameonthisfirstName/的依赖关系lastName

4

2 回答 2

3

试试这个:

(defn my-model [first last]
  (let [fname (.observable js/ko first)
        lname (.observable js/ko last)
        full-name (.computed js/ko #(str (fname) " " (lname)))] 
        (js-obj "firstName" fname
                "lastName" lname
                "fullName" full-name)))
于 2013-02-04T04:51:55.653 回答
1

重复@Ankur 的回答,您似乎还可以执行以下操作:

  (deftype AppViewModel [firstName lastName fullName])

  (defn my-model [first last]
    (AppViewModel. 
      (.observable js/ko "Bob") 
      (.observable js/ko "Smith")
      (.computed js/ko (str (firstName) " " (lastName)))))
于 2013-02-06T22:04:36.170 回答