这可能是一个非常初学的问题,或者我可能会同时使用太多东西。我正在尝试将KnockoutJS与Revealing Module Pattern一起使用并尝试编写CoffeeScript。我把我的模型放在一个单独的函数中。这是代码:
myapp =(->
person =->
firstname = ko.observable "k"
lastname = ko.observable "d"
firstname:firstname,
lastname:lastname
person : person
)()
$(->
ko.applyBindings(new myapp.person())
@
)
现在,这是使用Visual Studio中的工作台创建JavaScript,如下所示:
(function() {
var myapp;
myapp = (function() {
var person;
person = function() {
var firstname, lastname;
firstname = ko.observable("k");
lastname = ko.observable("d");
return {
firstname: firstname,
lastname: lastname
};
};
return {
person: person
};
})();
$(function() {
ko.applyBindings(new myapp.person());
return this;
});
}).call(this);
现在这给出了错误,它现在可以找到要绑定的元素。这是简单的HTML文本:
<p>
Firstname<span data-bind="text: myapp.person().firstname"></span>
Lastname<span data-bind="text: myapp.person().lastname">
</span>
</p>
如果我创建没有自我调用函数的普通JavaScript,它工作正常。这是功能:
myapp = (function () {
var person;
person = function () {
var firstname, lastname;
firstname = ko.observable("k");
lastname = ko.observable("j");
return {
firstname : firstname,
lastname : lastname
}
}
return {
person: person
}
})();
$(function () {
ko.applyBindings(new myapp.person());
})
有谁可以解释这里出了什么问题?或者是否有其他方法可以编写CoffeeScript来使用KnockoutJS?
如果需要进一步的详细信息,请发表评论。
答案 0 :(得分:1)
以下是工作示例:http://jsfiddle.net/gurkavcu/Kqa2k/
myapp = (->
person =->
firstname = ko.observable "jack"
lastname = ko.observable "sparrow"
firstname:firstname,
lastname:lastname
person : person
)()
$(->
ko.applyBindings(new myapp.person())
@
)
您需要更改绑定语法:
<p>
Firstname: <span data-bind="text:firstname"></span>
Lastname: <span data-bind="text:lastname">
</span>
</p>
因为当你调用ko.applyBindings(new myapp.person())时,你只为一个person对象而不是所有myapp对象设置你的视图。
如果要为整个myapp设置视图,则需要更改代码:
myapp = (->
person = (fname,lname)->
firstname = ko.observable fname
lastname = ko.observable lname
firstname:firstname,
lastname:lastname
person : new person("Jack" , "Sparrow")
)()
$(->
ko.applyBindings(myapp)
@
)
<p>
Firstname: <span data-bind="text:person.firstname"></span>
Lastname: <span data-bind="text:person.lastname">
</span>
</p>