我正试着用打字机和杜兰德尔打交道。我试图让初学者示例使用Type Script,它适用于大多数方法和类。但是在下面的flickr类中,我在select方法中遇到了一个问题。调用此方法时,似乎这不是flickr类,而是选定的项。
有人能帮我弄清楚怎么回事吗?
其他方法如预期的那样工作。
谨致问候,
马尔维
///<reference path='../../Scripts/typings/requirejs/require.d.ts'/>
///<reference path='../../Scripts/typings/durandal/durandal.d.ts'/>
///<reference path='../../Scripts/typings/knockout/knockout.d.ts'/>
class Flickr
{
app: App;
http: Http;
displayName = 'Flickr';
images = ko.observableArray([]);
constructor(app: App, http: Http)
{
this.app = app;
this.http = http;
}
public activate() : any
{
//the router's activator calls this function and waits for it to complete before proceding
if (this.images().length > 0)
{
return;
}
return this.http.jsonp('http://api.flickr.com/services/feeds/photos_public.gne', { tags: 'mount ranier', tagmode: 'any', format: 'json' }, 'jsoncallback').then((response)=>
{
this.images(response.items);
});
}
public select(item : any) {
//the app model allows easy display of modal dialogs by passing a view model
//views are usually located by convention, but you an specify it as well with viewUrl
item.viewUrl = 'views/detail';
this.app.showModal(item);
}
public canDeactivate() : any
{
//the router's activator calls this function to see if it can leave the screen
return this.app.showMessage('Are you sure you want to leave this page?', 'Navigate', ['Yes', 'No']);
}
}
define(['durandal/http', 'durandal/app'], function (http, app)
{
return new Flickr(app, http);
} );
编译成以下JavaScript:
var Flickr = (function () {
function Flickr(app, http) {
this.displayName = 'Flickr';
this.images = ko.observableArray([]);
this.app = app;
this.http = http;
}
Flickr.prototype.activate = function () {
var _this = this;
if(this.images().length > 0) {
return;
}
return this.http.jsonp('http://api.flickr.com/services/feeds/photos_public.gne', {
tags: 'mount ranier',
tagmode: 'any',
format: 'json'
}, 'jsoncallback').then(function (response) {
_this.images(response.items);
});
};
Flickr.prototype.select = function (item) {
item.viewUrl = 'views/detail';
this.app.showModal(item);
};
Flickr.prototype.canDeactivate = function () {
return this.app.showMessage('Are you sure you want to leave this page?', 'Navigate', [
'Yes',
'No'
]);
};
return Flickr;
})();
define([
'durandal/http',
'durandal/app'
], function (http, app) {
return new Flickr(app, http);
});
//@ sourceMappingURL=flickr.js.map
最佳答案
要使“this”引用视图模型,可以执行以下操作(假设flickr.html视图未被更改):
更改标记的缩略图上的单击绑定
<a href="#" class="thumbnail" data-bind="click:$parent.select">
到
<a href="#" class="thumbnail" data-bind="click: function (item) { $parent.select(item); }">
因为您正在直接调用$parent对象(视图模型)上的select方法,所以视图模型将绑定到“this”。
关于typescript - 选择不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15597620/