knockoutjs双向绑定示例需要

时间:2012-05-16 11:02:00

标签: knockout.js

淘汰赛真棒......同时我觉得有点沮丧......:|

继承我的代码

    <html>
    <head>


    @using MvcJqGrid;
    @using System.IO;
    @using System.Web.Mvc;
    @using System.Web.Script.Serialization;
    @{
        Layout = "";



        JavaScriptSerializer theSerializer = new JavaScriptSerializer();


        }





    <link rel="Stylesheet" type="text/css" href="Content/themes/base/jquery-ui.css" />
    <link rel="Stylesheet" type="text/css" href="Content/themes/base/jquery.ui.base.css" />
    <link rel="Stylesheet" type="text/css" href="Content/themes/base/jquery.ui.theme.css" />
    <link rel="Stylesheet" type="text/css" href="Content/ui.jqgrid.css" />


    <script type="text/javascript" src="Scripts/modernizr.custom.05850.js"></script>

    <script type="text/javascript" src="Scripts/jquery-1.7.2.js" > </script>

    <script type="text/javascript" src="Scripts/jquery-ui-1.8.19.js"> </script>

    <script  type="text/javascript"  src="Scripts/grid.locale-en.js" ></script>

    <script   type="text/javascript" src="Scripts/jquery.jqGrid.min.js"></script>

    <script type="text/javascript" src="Scripts/json2.min.js"></script>

    <script type="text/javascript" src="Scripts/knockout-2.1.0.js"></script>

    <script type="text/javascript" src="Scripts/knockout.mapping-latest.js"></script>

    <script type="text/javascript" src="Scripts/linq.min.js"></script>

    </head>



    <body>


    <!-- This is a *view* - HTML markup that defines the appearance of your UI -->

    <p>View Name: <input data-bind="value: Name " /></p>
    <p>No Of Results: <input data-bind="value: noOfResultsPerPage "/></p>


    <p id='filterEnable'>

     click me to invoke ajax service
    </p>


    <input type=text value="tester" id="testInput" />



<input type=text  value='test' data-bind='value:myComputedFilterExpression' id="linqTester" />



    <p id='myLabel' >
       container 

    </p>


    <p id='addFilterExpression' >add Filter</p>
    <table data-bind='visible: filterArray().length > 0'>
            <thead>
                <tr>
                    <th>filterExpression</th>
                    <th />
                    <th />
                </tr>
            </thead>
            <tbody data-bind='foreach: filterArray'>
                <tr>
                    <td data-bind"text :theExpression,value :theExpression"> 


                      Where  <select class='required' data-bind="options: $root.options, optionsCaption: 'Select...'" />    

                          <input type='text' id='uifix' style='display:none' />    

                                    <select class='required' data-bind="options: $root.filterExpressionValues, optionsCaption: 'Select...'" />

                          <input type='text' id='inputValue' />    
                            <select class='required' data-bind='options: $root.queryOptions,  optionsCaption: "Select..."' />



                    </td>

                    <td><a href='#' data-bind='click: $root.removeFilter'>Delete</a></td>
                    <td><a href='#' data-bind='click: $root.addFilter'>Add</a></td>


                </tr>
            </tbody>
        </table>



     <script type="text/javascript"> 
    $(function () {
        var viewModel = null;

         var  myOptions=@Html.Raw(PseudoSharepointView.getAllVariables()); 




        function FilterExpression()
        {    


         this.theExpression="";

        }

        function Success(data, status) {
            $("#myLabel").html(data.d);
        }

        function Error(request, status, error) {
            $("#myLabel").html(request.statusText);
        }

        $('#filterEnable').click(function () { 
            CallService();
        }); 



        var test=@Html.Raw(PseudoSharepointView.getAView());
        // Activates knockout.js 
        viewModel = ko.mapping.fromJS(test);
         viewModel.options=myOptions;
         viewModel.queryOptions=["and","or"];
         viewModel.filterExpressionValues=@Html.Raw(theSerializer.Serialize(PseudoSharepointView.SharepointColumn.FilterExpressionValues));
         var test=ko.mapping.toJS(viewModel);


         $("#testInput").val(JSON.stringify(test));


         viewModel.filterArray=ko.observableArray([new FilterExpression()]);



          viewModel.myComputedFilterExpression = ko.computed(function() {
            return Enumerable.From((viewModel.filterArray())).Select('$.theExpression').Aggregate("(a,b)=>a+''+b");
        });

        // Operations
        viewModel.addFilter = function() { 

        viewModel.filterArray.push(new FilterExpression());



        };
        viewModel.removeFilter = function(filter) {

        viewModel.filterArray.remove(filter) ;



        };




        ko.applyBindings(viewModel);




         $('#addFilterExpression').click(function () { 

         testArray= new Array();

         testArray[0]= new FilterExpression();
         testArray[0].theExpression="1";


         testArray[1]= new FilterExpression();
         testArray[1].theExpression="2";


          var test=Enumerable.From((viewModel.filterArray())).Select('$.theExpression').Aggregate("(a,b)=>a+''+b");


             $('#linqTester').val(test);
        }); 

        function CallService() {

            $.ajax({

                type: "POST",
                url: "myMethodsRepository.asmx/HelloWorld",
                data: "{viewValue:'"+JSON.stringify(ko.mapping.toJS(viewModel))+"'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: Success,
                error: Error
            });
        }



    });

    </script> 

    </body>
    </html>

我的问题如下

1)是否有必要完成双向绑定工作的事情.... cuz    ui更新肯定会发生,但实际值不会更新自己...    显然我错过了这里的东西

2)我的计算函数

viewModel.myComputedFilterExpression = ko.computed(function() {
        return Enumerable.From((viewModel.filterArray())).Select('$.theExpression').Aggregate("(a,b)=>a+''+b");
    });

似乎不起作用,因为变量没有自我更新

我使用了这个调试辅助工具

<input type=text  value='test' data-bind='value:myFilterExpression'  id="linqTester" />

希望你用数组

来构造所需的字符串表达式

我需要一个基本/ noob友好的解释,双向绑定到一个可观察的数组....如果有人想用我当前的代码显示它,上帝保佑他们...... :)

1 个答案:

答案 0 :(得分:8)

问题是myComputedFilterExpression是一个只读的计算函数,它返回一个可枚举的表达式。您期望通过价值绑定更新什么?

要进行计算的obervable读写,您需要像这样定义它。在可写计算的可观察量下的文档here中也有所涉及。

this.fullName = ko.computed({
    read: function () {
        return this.firstName() + " " + this.lastName(); 
    },
    write: function (value) {
        var lastSpacePos = value.lastIndexOf(" ");
        if (lastSpacePos > 0) { // Ignore values with no space character
            this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
            this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
        }
    },
    owner: this
});

当值绑定更新计算时,您会在define write函数中收到新值,并且您的工作就是将其映射到某个基础值。

希望这有帮助