2013-02-03 31 views
2

这里是JS的淘汰赛样片:方法定义为ClojureScript函数调用的结果

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.observableko.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中处理它?

同样,请注意fullNamethisfirstName/lastName的依赖关系。

+0

请注意,您目前只能传递一个字符串参数'.computed '。在你的JavaScript例子中,你传递一个函数和一个引用。 – eagleflo

回答

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))) 
1

上@ Riffing 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))))) 
+0

非常感谢!然而,它编译为:https://gist.github.com/konrad-garus/4733108 - “this”丢失,指“全球”的名字和姓氏... –

+0

哦,对,所以只需结合我的方法和@ ANKUR的。 – dnolen

相关问题