knockout.js,asp.net mvc4 - 使用getJSON数据更新simpel viewmodel

时间:2012-09-14 19:52:02

标签: jquery-mobile knockout.js asp.net-mvc-4

这是一个新手问题,更不用说我对knockout.js很新。我要做的就是从服务器获取单个种植者(名称,公司,地址)的详细信息并将其显示在网页上。我正在使用$(document).bind('pageinit',function(),因为我正在使用jQuery mobile。

现在我的代码是:

    <h3><span data-bind="text: Name"></span></h3>
    <span data-bind="text: Company"></span><br />
    <span data-bind="text: Address"></span>

    <script type="text/javascript">

       $(document).bind('pageinit', function () {

         function MyGrowerModel() {
            //this.Name = "My Name";
            //this.Company = "My Company";
            //this.Address = "My Address";

            //Load initial state from server, convert it to Task instances, then  opulate self.tasks
            $.getJSON("Grower/GetGrower", function (allData) {

             this.Name = allData.Name;
             this.Company = allData.Company;
             this.Address = allData.Address;
             alert(allData.Name); //works!
         });
        }

        ko.applyBindings(new MyGrowerModel());

       });
       </script>

我收到“无法解析绑定。消息:ReferenceError:未定义名称;绑定值:名称

这是有道理的,因为Name,Company和Address的范围是getJSON函数。所以,我的问题是,在哪里声明这些变量以及如何更新那些ViewModel数据?

我不想使用映射插件。

感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

您将要使用observable properties。这样,一旦您的$ .getJSON请求完成,您的视图将使用新数据进行更新。

<h3><span data-bind="text: Name"></span></h3>
<span data-bind="text: Company"></span><br />
<span data-bind="text: Address"></span>

<script type="text/javascript">

    function MyGrowerModel() {
        var self = this;
        self.Name = ko.observable('');
        self.Company = ko.observable('');
        self.Address = ko.observable('');

        self.Name.subscribe(function(newValue) {
            alert("Name has changed: " + newValue);
        });

        //Load initial state from server and populate viewmodel
        $.getJSON("Grower/GetGrower", function (allData) {
             self.Name(allData.Name);
             self.Company(allData.Company);
             self.Address(allData.Address);
        });
    }

   $(document).bind('pageinit', function () {
        ko.applyBindings(new MyGrowerModel());
   });
</script>