这是 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.compulated
各一个)返回一个函数。另请注意,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.compulated
的函数。也就是说,它编译为:
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 中处理它?</p>
再次注意 fullName
对 this
和 firstName
/lastName
的依赖性。
最佳答案
试试这个:
(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)))
关于clojure - ClojureScript 中函数调用结果的方法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14677098/