简体   繁体   中英

How to access NancyModule Properties in JavaScript?

In HTML I can access NancyModule properties with help of the Super Simple Engine View (SSVE) like this:

<label id="123"> @Model.PropertyName </Label> 

At runtime @Model.PropertyName will then be replaced by the actual value, which works great. ( More Information about this here )

What I am searching is a clean way to access these properties in JavaScript, but I didn't find any solution.

At the moment I load these properties in Labels (or whatever else), hide said Labels and access the properties in JavaScript over these Labels, which is a horrible, but working solution.

Does anyone know a clean and neat solution? Thank you in advance.

One option you have would be to adopt a client side javascript MVVM framework. There are a lot of frameworks out there to choose from, for instance KnockoutJs .

Using this approach you'll be able to cleanly orchestrate your client side app without having a mess of events and DOM manipulations.

Here's a basic example, cribbed from KnockoutJs's documentation, that shows how editing a text box automatically updates the view model (again there are many other options).

 // Here's my data model. You can setup using your Nancy model here. var ViewModel = function(first, last) { this.firstName = ko.observable(first); this.lastName = ko.observable(last); this.fullName = ko.computed(function() { // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName. return this.firstName() + " " + this.lastName(); }, this); }; ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work 
 body { font-family: arial; font-size: 14px; } .liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; } .liveExample input { font-family: Arial; } .liveExample b { font-weight: bold; } .liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; } .liveExample select[multiple] { width: 100%; height: 8em; } .liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div class='liveExample'> <p>First name: <input data-bind='value: firstName' /> </p> <p>Last name: <input data-bind='value: lastName' /> </p> <h2>Hello, <span data-bind='text: fullName'> </span>!</h2> </div> 

You can just write something like this:

<script type="text/javascript">    
    var 123 = @Model.PropertyName;
</script>       

Probably your IDE will mark this as wrong, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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