javascript - 使用 TypeScript 声明 Sammy js 设置
我刚刚在学习 KnockOut.js 教程,但将 JS 代码替换为 TS。在添加 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
谢谢
答案#1
我不确定这是否回答了你的问题,但你可以潜在地利用一个 TypeScript 定义文件,它描述了 Sammy,链接在这里 https://github.com/borisyankov/DefinitelyTyped/blob/master/sammyjs/sammyjs.d.ts 这个应该包含足够的 Sammy API 供你继续你的教程。
下载定义文件,并使用类似下面的特殊注释进行引用。
///<reference path="sammyjs/sammyjs.d.ts" />
答案#2
我知道这是一个老问题,但这确实给我带来了足够的痛苦,以至于值得为未来的访客提出建议。
我已经用 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 上对问题 19395335 的回答引导我找到了这个解决方案。
干杯。
