将knockoutjs视图模型传递给多个ajax调用

时间:2012-10-11 19:45:01

标签: ajax html5 knockout.js

我有一个函数,它调用ajax来获取初始数据并将其保存到viewmodel。然后,我将返回的viewmodel(将数据进行字符串化)传递给另一个进行另一个ajax调用的函数,依此类推。每个函数都绑定到onclick按钮事件。当我把它放在document.ready中时,我只能将初始视图模型传递给其他函数。我从每个函数得到的数据是100%正确的。但是,每当我绑定viewmodel时,它都会覆盖先前的绑定,并且值不成立。以下是代码:

的JavaScript

<

script type="text/javascript" language='javascript'>
        var MyProject = {};
        var viewModel;
        MyProject.viewModel = "";
        var invoiceModel;
        $(document).ready(function InitializeInvoice() {
                    $.ajax({
                        type: "Post",
                        url: "Default.aspx/InitializeModel",
                        data: {},
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: false,
                        success: initializesinvoice
                    });
                function initializesinvoice(msg) {
                    var defaultdata = msg.d.Data;
                    invoiceModel = defaultdata;
                    MyProject.viewModel = ko.mapping.fromJS(invoiceModel);
                    ko.applyBindings(MyProject.viewModel)
                };
            })
            function GetVendorInvoiceDefaults() {
                MyProject.viewModel = JSON.stringify(invoiceModel);
                var data = '{invoice:' + MyProject.viewModel + '}';
                $.ajax({
                    type: "Post",
                    url: "Default.aspx/GetVendorInvoiceDefaults",
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: GetVendorInvoiceDefaultsSuccess
                });
            }
            function GetVendorInvoiceDefaultsSuccess(msg) {
                var defaultdata = msg.d.Data;
                invoiceModel = defaultdata;
                MyProject.viewModel = ko.mapping.fromJS(invoiceModel);
                ko.applyBindings(MyProject.viewModel)
            };

             function GetVendorCode() {
                var vendormodel = JSON.stringify(invoiceModel);
                var data = '{invoice:' + vendormodel + '}';
                $.ajax({
                    type: "Post",
                    url: "Default.aspx/GetVendorCode",
                    data: '{invoice:' + vendormodel + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: GetVendorCodeSucess
                });
            }

            function GetVendorCodeSucess(msg) {
                var defaultdata = msg.d.Data;
                MyProject.viewModel = ko.mapping.fromJS(defaultdata);
                ko.applyBindings(MyProject.viewModel)
            };
#HTML#
    <p> Invoice Description <asp:TextBox ID="txtdesc" runat="server" data-bind="value:InvoiceDescription"> </asp:TextBox></p>    
    <p> Distribution Code <asp:TextBox ID="txtdistcode" runat="server" data-bind="value:DistributionCode"></asp:TextBox></p>
    <p> Vendor Code <asp:TextBox ID="txtvendor" runat="server" data-bind="value:VendorCode" ></asp:TextBox></p>
    <p> <button onclick="InitializeInvoice()">InitializeInvoice</button></p>
    <p><button id="btndefaults" onclick="GetVendorInvoiceDefaults()">GetVendorInvoiceDefaults</button></p>
    <p><button id="btnvendor" onclick="GetVendorCode()">GetVendorCode</button><p>
</pre>

#ASPX file#
    namespace WebApplication9
    {

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {


        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsPostBack)
            {

                clientSideIsPostBack.Value = "Y";
            }

            else
                    clientSideIsPostBack.Value = "N";

                base.OnLoad(e);
        }

        [WebMethod]
        public static JsonResult  InitializeModel()
        {

            var Invoice = new Invoice() { InvoiceNumber = "1235", InvoiceDescription = "Hello World", DistributionCode = "" };
            JsonResult r = new JsonResult();
            r.Data = Invoice;
            return r;    //serializer.Deserialize(Invoice, typeof(Invoice)) as JsonResult;
        }

        [WebMethod]
        public static JsonResult GetVendorInvoiceDefaults(Invoice invoice)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            invoice.DistributionCode = "HELLO WORLD";
            JsonResult r = new JsonResult();
            r.Data = invoice;
            return r;
            //return new JsonResult() { Data = invoice };
        }

        [WebMethod]
        public static JsonResult GetVendorCode(Invoice invoice)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            invoice.VendorCode = "AHM";
            JsonResult r = new JsonResult();
            r.Data = invoice;
            return r;
        }

    }


    public class Invoice
    {
        private string distributionCode;
        private string vendorcode;

        public string InvoiceNumber { get; set; }
        public string InvoiceDescription { get; set; }
        public string DistributionCode 
        {
            get
            {
                return distributionCode ?? string.Empty;
            }
            set
            {
                distributionCode = value;
            }
        }
        public string VendorCode 
        {
            get
            {
                return vendorcode ?? string.Empty;

            }
            set 
            {
                vendorcode = value;

            }
        }

    }
    }

1 个答案:

答案 0 :(得分:3)

所以,你不应该在多个地方或不止一次(每个div)进行这个调用ko.applyBindings(MyProject.viewModel).

一旦应用了视图模型的绑定,就会应用它们。 你永远不会重复这一步!这非常重要。更新MyProject.viewModel中的值时,绑定会自动更新HTML。这就是重点。当您不止一次致电applyBindings时,您将创造各种意外行为。

设置viewModel,applyBindings一次,然后使所有其他代码正确更新viewmodel。我建议在做其他事之前在document.ready处理程序中执行此操作,例如连接ajaxy。

其次,在使用KO Mapping插件per the documentation时,您更新整个视图模型,如下所示:ko.mapping.fromJS(data, viewModel);每次调用MyProject.viewModel = ko.mapping.fromJS(invoiceModel);都会覆盖您的视图模型。

这是Knockout的另一个关键方面。因为observable是函数,所以你可以通过将新值作为参数传递来更新它们,而不是像普通变量一样覆盖它们。

右:

viewModel.observable(newValue)

错:

viewModel.observable = newvalue