使用ScriptSharp来编写Knockout.js代码

Knockout.js 可以帮助你使用Model-View-ViewModel (MVVM) 模式构建UI.

本文以 http://learn.knockoutjs.com/ 提供的示例为基础,提供ScriptSharp版本的实现.

关于ScriptSharp快速入门的知识,请参考:http://www.cnblogs.com/laojia/archive/2011/09/29/2195611.html.

本示例的ScriptSharp项目模板为Jquery Library,建完项目之后,需要手工添加位于ScriptSharp安装文件夹下的Script.Knockout.dll的引用.

直接贴上代码:

Page.cs

using System;
using System.Runtime.CompilerServices;
using jQueryApi;
using KnockoutApi;
using ScriptSharpKnockout.KnockoutTutorial;

namespace ScriptSharpKnockout
{
    [GlobalMethods]
    internal static class Page
    {
        static Page()
        {
            jQuery.OnDocumentReady(delegate { Knockout.ApplyBindings(new ViewModel()); });
        }
    }
}

 

ViewModel.cs

 

using KnockoutApi;

namespace ScriptSharpKnockout.KnockoutTutorial
{
    public class ViewModel
    {
        public Observable<string> FirstName = Knockout.Observable<string>("first Name");
        public Observable<string> LastName = Knockout.Observable<string>("last Name");
        public DependentObservable<string> FullName;

        public ViewModel()
        {
            FullName = Knockout.DependentObservable<string>(
                delegate
                {
                    return "你好:" + FirstName.GetValue() + "  " + LastName.GetValue();
                });
        }

        public void UpdateValue()
        {
            this.LastName.SetValue(this.LastName.GetValue().ToUpperCase());
        }
    }
}

 

index.htm

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
    <script type="text/javascript" src="../bin/Debug/mscorlib.debug.js"></script>
    <script type="text/javascript" src="../bin/Debug/jquery-1.6.2.js"></script>
    <script type="text/javascript" src="../bin/Debug/knockout-1.2.1.js"></script>
    <script type="text/javascript" src="../bin/Debug/ScriptSharpKnockout.debug.js"></script>
</head>
<body>
    <p>
        First name:
        <input data-bind="value:firstName" /></p>
    <p>
        Last name:
        <input data-bind="value:lastName" /></p>
    <p data-bind="text:fullName">
    </p>
    <input type="button" value="update showInfo" data-bind="click:updateValue" />
</body>
</html>

附上项目文件包以供下载测试:http://files.cnblogs.com/laojia/ScriptSharpKnockout.zip

你可能感兴趣的:(使用ScriptSharp来编写Knockout.js代码)