简体   繁体   English

将razor视图内联javascript移动到外部打字稿文件

[英]move razor view inline javascript to external typescript file

I had a razor view with inline javascript which with time has become messy, and now I am moving all js (except some minimal initialization code) to external typescript file. 我有一个内联javascript的剃刀视图,随着时间的推移,它变得一团糟,现在我将所有js(一些最小的初始化代码除外)移至外部打字稿文件。 It would be nice to make the js code reusable, but it is very much specific to this particular view. 使js代码可重用会很好,但是它非常特定于此特定视图。 The js code depends heavily on many html elements. js代码在很大程度上取决于许多html元素。 What I have is something like this: 我所拥有的是这样的:

module MyModule{

export class SomeClass{

    private $counter: any;
    private $answers: any;
    private $pager: any;
    private $anotherSelector1:any;
    private $anotherSelector2:any;
    private $anotherSelector3:any;
    private $anotherSelector4:any;
    private someId: number;

    constructor(public options: any) {

        this.init(options);

    }

    private init(options) {
        //setup objects, callbacks, other init code
    }
}
} 

and I call it from my cshtml file like this: 然后从我的cshtml文件中这样调用它:

 $(document).ready(function () {

        var instance = new MyModule.SomeClass({
            $counter: $('#something'),
            $answers: $('#something'),
            $pager: $('#something'),
            //code omitted for brevity
            someId: "@Model.SomeId",

        });


    });

It seems to me that even though this approach will result in a more clean razor view, the typescript file will still have many dependencies to the html DOM. 在我看来,即使这种方法将导致更清晰的剃刀视图,但打字稿文件仍将对html DOM具有许多依赖性。 Am I doing it right? 我做对了吗? Should I consider refactoring the html in the view as well? 我是否应该考虑在视图中重构HTML? Also, should I move the init code in the cshtml file to the ts file as well or should I leave it like it is? 另外,我应该将cshtml文件中的init代码也移到ts文件中还是应该保持原样? I am kind of looking for best practices when doing refactorings like this. 在进行这样的重构时,我正在寻找最佳实践。

I don't think you are doing it wrong :) though I understand your concern. 我不认为您做错了:)尽管我了解您的担心。

I think the problem you are wanting to solve is kinda like a cleaner javascript without depending on DOM selectors, it seems you actually want something like knockoutjs or angularjs which is basically some kind of templating approach. 我认为您要解决的问题有点像更清洁的JavaScript,而无需依赖DOM选择器,看来您实际上想要的是类似基因敲除 jsangularjs的东西,这基本上是一种模板化方法。 Checkout there demo's for how it is done. 在演示中查看如何完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM