使用TypeScript声明Sammy js设置

时间:2012-12-17 10:04:19

标签: javascript knockout.js typescript sammy.js

我刚刚浏览了KnockOut.js教程,但用TS替换了JS代码。添加SammyJS时,我坚持使用以下代码。任何人都可以建议TS中的Sammy函数代码吗?

function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
self.chosenFolderData = ko.observable();
self.chosenMailData = ko.observable();

// Behaviours    
self.goToFolder = function(folder) { location.hash = folder };
self.goToMail = function(mail) { location.hash = mail.folder + '/' + mail.id };

// Client-side routes    
Sammy(function() {
    this.get('#:folder', function() {
        self.chosenFolderId(this.params.folder);
        self.chosenMailData(null);
        $.get("/mail", { folder: this.params.folder }, self.chosenFolderData);
    });

    this.get('#:folder/:mailId', function() {
        self.chosenFolderId(this.params.folder);
        self.chosenFolderData(null);
        $.get("/mail", { mailId: this.params.mailId }, self.chosenMailData);
    });

    this.get('', function() { this.app.runRoute('get', '#Inbox') });
}).run();    
};

ko.applyBindings(new WebmailViewModel());

我关注的教程是http://learn.knockoutjs.com/#/?tutorial=webmail

由于

2 个答案:

答案 0 :(得分:1)

我不确定这是否能解答您的问题,但您可以利用在此处描述Sammy的TypeScript定义文件https://github.com/borisyankov/DefinitelyTyped/blob/master/sammyjs/sammyjs.d.ts这应该有足够的sammy api供您继续学习。< / p>

使用类似下面的特殊注释下载定义文件和参考。

///<reference path="sammyjs/sammyjs.d.ts" />

答案 1 :(得分:0)

我知道这是一个老问题,但这确实给我带来了足够的痛苦,值得为未来的访客提供建议。

我在TypeScript中重写了上面的示例代码。

/// <reference path="../Scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../Scripts/typings/Sammy/Sammy.d.ts" />
import sammy = require("sammy");
class WebmailViewModel
{
    // Data
    public folders: Array<string> = ['Inbox', 'Archive', 'Sent', 'Spam'];
    public chosenFolderId: KnockoutObservable<any> = ko.observable();
    public chosenFolderData: KnockoutObservable<any> = ko.observable();
    public chosenMailData: KnockoutObservable<any> = ko.observable();

    // Behaviours    
    public goToFolder = function (folder) { window.location.hash = folder };
    public goToMail = function (mail) { window.location.hash = mail.folder + '/' + mail.id };

    // Client-side routes    
    public SammyApp: sammy.Application =
    Sammy().get('#:folder', context =>
    {
        this.chosenFolderId(context.params.folder);
        this.chosenMailData(null);
        $.get("/mail", { folder: context.params.folder }, this.chosenFolderData);
    }).get('#:folder/:mailId', context =>
    {
        this.chosenFolderId(context.params.folder);
        this.chosenFolderData(null);
        $.get("/mail", { mailId: context.params.mailId }, this.chosenMailData);
    }).get('', context =>
    {
        context.app.runRoute('get', '#Inbox');
    }).run();
};

然后,在$(document).ready()

var viewModel = new WebmailViewModel;
ko.applyBindings(viewModel);

非常感谢@Vladimir的回答stack overflow question 19395335 引导我找到解决方案。

干杯。

相关问题