简体   繁体   English

如何使用基因剔除获得可观测值

[英]How to get the value of an observable using knockout

I'm trying to access to the value of an observable from an other script that the one where the view model is defined, but I've no idea how to do that. 我正在尝试从定义视图模型的另一个脚本访问可观察值,但是我不知道该怎么做。 Let me explain the thing: 让我解释一下:

My view model is defined in monitoringviewmodel.js and used in MonitoringTask.cshtml where I display the data passed from it. 我的视图模型中定义monitoringviewmodel.js和在使用MonitoringTask.cshtml其中I显示从它传递的数据。 In this webpage, I've a select list where the user can choose in which page they want to go. 在此网页中,我有一个选择列表,用户可以在其中选择他们要进入的页面。 My idea was to store the link in the value parameter of each option . 我的想法是将链接存储在每个optionvalue参数中。 Then I would get which link the user choosed, and I would use their value to redirect them to the right page. 然后,我将获得用户选择的链接,并使用其值将其重定向到正确的页面。 In order to get the right data, I've decided to put an id on the select to identify it simply (my data are shown using a foreach , so I cannot just select the select tag bc it apears multiple time in the page). 为了获得正确的数据,我决定在select上添加一个id以便简单地标识它(我的数据使用foreach来显示,因此我不能仅仅选择它多次出现在页面中的select标记)。 The id is put through an observable from knockout.js . id会通过来自knockout.js的观察对象进行放置。 My problem is that I don't know how to get the value of this observable in a script in my webpage. 我的问题是,我不知道如何在网页脚本中获取此可观察值。

If you have any idea how to do that... 如果您有任何想法...

Thanks 谢谢

If you have the id: 如果您有ID:

var element = document.getElementById(id);
var viewModel = ko.dataFor(element);
var value = viewModel.observable();

@Rajesh: the definition of my viewmodel is separated from the webpage. @Rajesh:我的视图模型的定义与网页分开。 I want to have access the value of my observable from my webpage, that's why I can't just use observableVariable() in the script in my webpage. 我想从我的网页访问我的observable的值,这就是为什么我不能只在我的网页脚本中使用observableVariable()的原因。

@frooook : because I use a foreach binding, and bc my id is generated in the viewmodel in the monitoringviewmodel.js file, I don't have the id of the element. @frooook:因为我使用了foreach绑定,并且bc我的id是在monitoringviewmodel.js文件的viewmodel中生成的,所以我没有该元素的id。

If the things aren't clear (and bc @samuellawrentz asked me to put it ^^), here's the code I used (it requires the library require.js and other bunch of files to work properly, so it won't run as it is, but this is the main part that deals with the data, the rest that is not included works perfectly fine): 如果事情不清楚(bc @samuellawrentz让我把它放^^),这是我使用的代码(它需要库require.js和其他文件才能正常工作,因此它不能像是的,但这是处理数据的主要部分,未包含的其余部分则很好用):

monitoringviewmodel.js : monitoringviewmodel.js

define([
    'common'
], function () {
    'use strict';
    //1000 ms = 1 second
    var callSmtpCheckTmp = 3600000; // chaque 1 heure
    var callBdCheckTmp = 600000; // chaque 10 min
    var checkServiceTmp = 60000; // chaque 1 min
    var checkFirstSmtpTmp = 60000; // chaque minute
    var checkRunningTmp = 10000; //chaque seconde
    var checkStatusTmp = 60000;// chaque minute
    var ko = require('knockout');

    var ViewModel = function (message) {
        var _this = this;

        _this.listService = ko.observableArray(
            ko.utils.arrayMap(message.ListServiceModel, function (elem) {
                return new ServiceViewModel(elem);
            }));

        var sizeColumns = ComputeSizeColumns();
        ko.utils.arrayForEach(_this.listService(), function(elem) {
            elem.sizeColumns = sizeColumns;
        })

        CheckBdData();

        // All the functions below work perfectly fine and are not releveant to the topic

        function CheckBdData() { ... }

        function ComputeSizeColumns() { ... }

        $(window).load(function () {
            setInterval(CheckBdData, callBdCheckTmp);
        });
    };

    var ServiceViewModel = function (items) {
        var _this = this;

        var checkFirstSmtp = true;
        _this.id = ko.observable(items.Id);
        _this.serviceName = ko.observable(items.ServiceName);
        _this.description = ko.observable(items.Description);
        _this.serviceUrl = ko.observable(items.ServiceUrl);
        _this.status = ko.observable(false);
        _this.checkSmtp = ko.observable(true);

        _this.listTask = ko.observableArray(
            ko.utils.arrayMap(items.ListTaskModel, function (elem) {
                return new TaskViewModel(elem, items.ServiceUrl, items.Id, _this.checkSmtp);
            }));

        _this.profitStatus = ko.computed(function () {
            var css = '';
            if (_this.status() === true) {
                // css = "statusOk";
                css = "glyphicon-ok";
            }
            else {
                // css = "statusKO";
                css = "glyphicon-remove";
            }
            return css;
        });
        _this.sizeColumns = ko.observable("");

        checkStatus();

        // All the functions below work perfectly fine and are not releveant to the topic

        function checkStatus() { ... }

        function CheckSMTPTask() { ... }

        function CheckFirstSMTPTask() { ... }

        $(window).load(function () {
            setInterval(checkStatus, checkServiceTmp);
            setInterval(CheckSMTPTask, callSmtpCheckTmp);
            setInterval(CheckFirstSMTPTask, checkFirstSmtpTmp);
        });
    };

    var TaskViewModel = function (items, serviceUrl, serviceId, checkSmtp) {
        var _this = this;
        var urlTask = serviceUrl + items.DisplayName + "/";
        var errorLinkStr = new Link("Erreurs", "/Monitoring/ViewError?environnementId=" + environnementId + "&serviceId=" + serviceId + "&taskId=" + items.Id);
        var histLinkStr = new Link("Historique", "/Monitoring/ViewHistory?environnementId=" + environnementId + "&serviceId=" + serviceId + "&taskId=" + items.Id);
        var configLinkStr = new Link("Config", urlTask + "config");
        var statusLinkStr = new Link("État", urlTask + "status");
        var IdPopoverStr = 'Popover' + items.DisplayName;
        _this.id = ko.observable(items.Id);
        _this.serviceId = ko.observable(serviceId);
        _this.displayName = ko.observable(items.DisplayName);
        _this.bdName = ko.observable(items.BdName);
        _this.serviceUrl = ko.observable(serviceUrl + items.DisplayName + "/");
        _this.description = ko.observable(items.Description);
        _this.status = ko.observable('');
        _this.nextExecution = ko.observable(items.NextOccurrenceToString);
        _this.nbExec = ko.observable(items.NbExec);
        _this.nbError = ko.observable(items.NbError);
        _this.serviceUrl = ko.observable(items.ServiceUrl);
        _this.lastExec = ko.observable(items.LastExec);
        _this.execTaskLink = ko.observable(urlTask + "exec");
        _this.errorLink = ko.observable(errorLinkStr.link);
        _this.histLink = ko.observable(histLinkStr.link);
        _this.configLink = ko.observable(configLinkStr.link);
        _this.statusLink = ko.observable(statusLinkStr.link);
        _this.runningLink = ko.observable(urlTask + "isrunning");
        _this.isrunning = ko.observable(false);
        _this.checkBdd = ko.observable(false);
        _this.arrayLinks = ko.observableArray([errorLinkStr, histLinkStr, configLinkStr, statusLinkStr]);
        _this.Selectedlink = ko.observable();
        _this.IdPopover = IdPopoverStr;
        _this.IdPopoverCall = "#" + IdPopoverStr;
        _this.PopoverContent = ko.observable("Tâche : " + items.DisplayName+ "\nDescription : " + items.Description);
        _this.profitStatus = ko.computed(function () {
            var css = '';
            if (_this.status() === true) {
                //css = "statusOk";
                css = "success";
            }
            else {
                //css = "statusKO";
                css = "danger";
            }
            return css;
        });
        checkStatus();

        // All the functions below work perfectly fine and are not releveant to the topic

        function checkStatus() { ... }

        function RunningTask() { ... }

        $(window).load(function () {
            setInterval(checkStatus, checkStatusTmp);
            setInterval(RunningTask, checkRunningTmp);
        });

        CheckBddTask(_this);
    };

    var Link = function(name, link){
        this.name = name;
        this.link = link;
    }

    // All the functions below work perfectly fine and are not releveant to the topic

    function CheckStatusTask(task, checkSmtp) { ... }

    function CheckRunningTask(task) { ... }

    function CheckStatusService(service) { ... }

    function CheckSMTPTaskService(service) { ... }

    function CheckBddTask(task) { ... }

    function GetBdInfo(listTask) { ... }

    return ViewModel;
});

MonitoringTask.cshtml : MonitoringTask.cshtml

 <!-- The rest of the webpage works perflectly fine, the part below is the one that deals with the data from knockout.js --> <table> <tr> <td> <div data-bind="foreach: { data: listService, as: 'service' }"> <table class="table table-responsive"> <thead> <tr> <td colspan=8 > <h3> <span data-bind="text: service.serviceName"></span> </h3> </td> <td><span style="font-size:20px;" class="icon-ok-notok glyphicon" data-bind="css: service.profitStatus"></span></td> </tr> <tr> <th>Tâche</th> <th class="hidden-xs hidden-sm hidden-md">Description</th> <th>État</th> <th>Prochaine Exec</th> <th>Dernière Exec</th> <th>Nb Exec</th> <th>Nb Error</th> <th>Forcer l'exec</th> <th>Visualisation</th> </tr> </thead> <tbody data-bind="foreach: { data: listTask, as: 'item' }"> <tr data-bind="css: {danger: (!item.status() && $parent.status()), success: !(!item.status() && $parent.status())}"> <td> <span data-bind="text: item.displayName"></span> </td> <td class="hidden-xs hidden-sm hidden-md"> <span data-bind="text: item.description"></span> </td> <td> <span class="glyphicon" data-bind="css : {'glyphicon-ok': item.status(), 'glyphicon-remove': !item.status()}"></span> </td> <td class="noWrap" align="center"> <span data-bind="text: item.nextExecution"></span> </td> <td> <span data-bind="text: item.lastExec"></span> </td> <td> <span data-bind="text: item.nbExec"></span> </td> <td> <span data-bind="text: item.nbError"></span> </td> <td> <a data-bind="attr: { href: item.execTaskLink}" target="_blank"><span class="glyphicon glyphicon-new-window"></span></a> </td> <td> <select data-bind="attr: {id: item.displayName}, options: arrayLinks, optionsText: 'name', value: Selectedlink, optionsValue: 'link', optionsCaption:'Visualiser...'"></select><br/> <span data-bind="visible: Selectedlink">Lien : <a data-bind="attr: {href: Selectedlink() ? Selectedlink : '#'}" target="_blank"><span class="glyphicon glyphicon-new-window"></span></a></span> <span style="display: none;" data-bind="text: item.displayName"></span> </td> </tr> </tbody> </table> </div> </td> </tr> </table> 

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

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