1

这可能是非常初学者的问题,或者我一次使用了太多东西。我正在尝试将 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?

如果需要更多详细信息,请发表评论。

4

1 回答 1

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()) 时,您仅为一个人对象而不是所有 myapp 对象设置视图。

如果要为整个 myapp 设置视图,则需要像这样更改代码:

JSfiddle 链接

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>​
于 2012-08-02T14:15:52.657 回答