如何根据数据绑定在挖空对象中加载特定元素?

时间:2017-06-14 08:24:12

标签: javascript jquery html knockout.js

enter image description here

我想要做的是,我想根据与链接数据绑定的特定敲除元素加载一个knockout元素。进一步说明如下:

我将一个敲除元素(称为applicationKey)数据绑定到下面的链接。

 <div class="col-md-12" style="text-align: right">
           <a href="#" data-toggle="modal" data-target="#my_modal" data-bind="attr: { 'data-applicationKey': application.applicationKey }">
             Preview Application
           </a>
       </div>

当我检查链接的元素时,

<a href="#" data-toggle="modal" data-target="#previewApplicantModal" data-bind="attr: { 'data-applicationKey': application.applicationKey }" data-applicationkey="abc976cfx">                                                                       
      Preview Application                                                                    
 </a>

我可以看到作为淘汰内容的applicationKey(data-applicationkey =“abc976cfx”)被成功绑定。

当我点击链接时,它应该给我一个以这​​种方式编码的模态:

<div id="previewApplicantModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Applicant Preview</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <span>Applicant Location</span>
                    </div>
                    <div class="col-md-6">
                        <div>
                        </div>
                    </div>
                </div>
                <div class="row small-margin-top" style="text-align:center">
                    <a href="#">Read Full Profile</a>
                </div>

            </div>

        </div>
    </div>
</div>

我想通过放置

来显示图像上显示的“candidateLocation”元素
<span data-bind="text: application.candidateLocation"></span>

在模型体内部,但当我这样做时,我收到一条消息说

Message: application is not defined

我假设有一个特定的方法来做这个与淘汰赛js。如何显示我想要的knockout元素(本例中为candidateLocation)对应于特定的knockout元素(本例中为applicationKey)?

请帮助!!感谢

编辑:Javscript部分

    <script type="text/javascript">

        $("#jobActionsPopup").dialog({
            dialogClass: "no-close",
            position: { my: "middle top", at: "middle bottom", of: $("#jobActionsButton") },
            autoOpen: false,
            draggable: true,
        }).dialog("widget").find(".ui-dialog-titlebar").hide();


        function ViewModel() {


    var self = this;

    self.invite = ko.observable(false);

    self.changeStylesInvite = function () {
        self.invite(true);
    }

    self.notifications = ko.observableArray(@Html.Json(Model.Notifications.Select(o => o.JsonForm)) || []);

    self.applications = ko.observableArray(@Html.Json(Model.ApplicationCompatibilities.Select(o => o.JsonForm)) || []);
    self.applicationInvitations = ko.observableArray(@Html.Json(Model.ApplicationInvitations.Select(o => o.JsonForm)) || []);

    self.applicationsFilter = ko.observable("new");
    self.showHiddenApplications = ko.observable(false);

    self.newApplicationsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.applications(), function(i) {
            return !i.application.isShortlisted && !i.application.isContactInfoSent && (self.showHiddenApplications() || !i.application.isHidden);
        }).length;
    });
    self.shortlistedApplicationsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.applications(), function(i) {
            return i.application.isShortlisted && (self.showHiddenApplications() || !i.application.isHidden);
        }).length;
    });
    self.connectedApplicationsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.applications(), function(i) {
            return i.application.isContactInfoSent && (self.showHiddenApplications() || !i.application.isHidden);
        }).length;
    });
    self.allApplicationsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.applications(), function(i) {
            return (self.showHiddenApplications() || !i.application.isHidden);
        }).length;
    });
    self.filteredApplications = ko.computed(function() {
        if(self.applicationsFilter() == 'new') {
            return ko.utils.arrayFilter(self.applications(), function(i) {
                return !i.application.isShortlisted && !i.application.isContactInfoSent && (self.showHiddenApplications() || !i.application.isHidden);
            });
        }
        else if(self.applicationsFilter() == 'shortlisted') {
            return ko.utils.arrayFilter(self.applications(), function(i) {
                return i.application.isShortlisted && (self.showHiddenApplications() || !i.application.isHidden);
            });
        }
        else if(self.applicationsFilter() == 'connected') {
            return ko.utils.arrayFilter(self.applications(), function(i) {
                return i.application.isContactInfoSent && (self.showHiddenApplications() || !i.application.isHidden);
            });
        }
        else if(self.applicationsFilter() == 'all') {
            return ko.utils.arrayFilter(self.applications(), function(i) {
                return (self.showHiddenApplications() || !i.application.isHidden);
            });
        }
        else {
            console.error('error in filteredApplications, unhandled applicationsFilter: ' + self.applicationsFilter());
            return self.applications(); // return all by default
        }
    });

    self.interviews = ko.observableArray(@Html.Json(Model.Interviews.Select(o => o.JsonForm)) || []);
    self.offers = ko.observableArray(@Html.Json(Model.Offers.Select(o => o.JsonForm)) || []);

    self.bulkHideApplications = ko.computed(function() {
        return ko.utils.arrayFilter(self.applications(), function(i) {
            return !i.application.isShortlisted && !i.application.isContactInfoSent && !i.application.isHidden;
        });
    });
    self.bulkHideApplicationKeys = ko.computed(function() {
        return self.bulkHideApplications().map(function(obj) { return obj.application.applicationKey; }).join();
    });

    self.jobQuestions = ko.observableArray(@Html.Json(Model.Job.JobQuestions.Select(o => o.JsonForm)) || []);
    self.jobQuestionsFilter = ko.observable("new");
    self.newJobQuestionsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
            return !i.ignored && i.answer == null;
        }).length;
    });
    self.ignoredJobQuestionsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
            return i.ignored;
        }).length;
    });
    self.answeredJobQuestionsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
            return i.answer != null;
        }).length;
    });
    self.allJobQuestionsCount = ko.computed(function() {
        return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
            return true;
        }).length;
    });
    self.filteredJobQuestions = ko.computed(function() {
        if(self.jobQuestionsFilter() == 'new') {
            return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
                return !i.ignored && i.answer == null;
            });
        }
        else if(self.jobQuestionsFilter() == 'ignored') {
            return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
                return i.ignored;
            });
        }
        else if(self.jobQuestionsFilter() == 'answered') {
            return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
                return i.answer != null;
            });
        }
        else if(self.jobQuestionsFilter() == 'all') {
            return ko.utils.arrayFilter(self.jobQuestions(), function(i) {
                return true;
            });
        }
        else {
            console.error('error in filteredJobQuestions, unhandled jobQuestionsFilter: ' + self.jobQuestionsFilter());
            return self.jobQuestions(); // return all by default
        }

    });

    self.ignoreJobQuestion = function(jobQuestion) {
        handle(jobQuestion, "&action=ignore");
    };
    self.answerJobQuestion = function(jobQuestion) {
        handle(jobQuestion, "&action=answer");
    };
    self.editJobQuestion = function(jobQuestion) {
        handle(jobQuestion, "&action=edit");
    };
    self.makePublicJobQuestion = function(jobQuestion) {
        handle(jobQuestion, "&action=makePublic");
    };
    self.makePrivateJobQuestion = function(jobQuestion) {
        handle(jobQuestion, "&action=makePrivate");
    };
    function handle(jobQuestion, actionQueryString) {
        $.ajax({
            type: "POST",
            url: '@MVC.GetLocalUrl(MVC.HireOrgJob.AjaxAnswerQuestion(Model.Job))',
            data: $('form#jobQuestionForm_' + jobQuestion.id).serialize() + actionQueryString,
            success: function (msg) {
                var index = self.jobQuestions.indexOf(jobQuestion);
                self.jobQuestions.remove(jobQuestion); // remove and splice instead of replacing because the object properties are not ko.observables, so remove and insert will update the UI
                self.jobQuestions.splice(index, 0, msg);
            },
            error: function () {
                alert("failure");
            }
        });
    };
};

var viewModel;
$(function () {
    viewModel = new ViewModel();
    ko.applyBindings(viewModel);

    $('form#pauseJobForm').ajaxForm(function(msg) {
        alert('paused');
        location.reload(); // refresh page to show result
        // nothing to do with the result... viewModel.isHidden(false);
    });

    $('form#unpauseJobForm').ajaxForm(function(msg) {
        alert('resumed');
        location.reload(); // refresh page to show result
        // nothing to do with the result... viewModel.isHidden(false);
    });

    $('form#endJobForm').ajaxForm(function(msg) {
        alert('closed');
        location.reload(); // refresh page to show result
        // nothing to do with the result... viewModel.isHidden(false);
    });

    $('form#SetViewProfileModeForm').ajaxForm(function(msg) {
        alert('saved view profile mode: ' + JSON.stringify(msg));
        //location.reload(); // refresh page to show result
        // nothing to do with the result... viewModel.isHidden(false);
    });

    $('form#setBiasFreeModeForm').ajaxForm(function(msg) {
        alert('saved bias free mode: ' + JSON.stringify(msg));
        location.reload(); // refresh the page to change the knockout viewmodels (name, etc.)
        // nothing to do with the result... viewModel.isHidden(false);
    });
    $('form#hideMultipleApplicationsForm').ajaxForm(function(msg) {
        alert("saved");
        location.reload(); // refresh page to show result
        // nothing to do with the result... viewModel.isHidden(false);
    });

    $('form#inviteToApplyForm').ajaxForm(function(msg) {
        viewModel.applicationInvitations.push(msg);
        $('.modal').modal('hide');
        alert('invited!');
        //location.reload(); // refresh page to show result
        // nothing to do with the result... viewModel.isHidden(false);
    });

    $('form#addManualApplicationForm').ajaxForm(function(msg) {
        viewModel.applications.push(msg);
        $('.modal').modal('hide');
        $('form#addManualApplicationForm').resetForm();
        $('#showNickNameFullNameA').show();
        $('#nickNameFullNameDiv').hide();
        $('#addCoverLetterA').show();
        $('#addCoverLetterDiv').hide();
        $('#addTextResumeA').show();
        $('#addTextResumeDiv').hide();

    });
});

    </script>
}

1 个答案:

答案 0 :(得分:1)

我会在viewModel上使用一个observable来跟踪当前应用程序,即将在模态上显示的应用程序。它的名字可以是“currentApplication”。

这是一个有效的jsfiddle: https://jsfiddle.net/matiasm/3v3c7hkf/4/

function application ( applicationKey, location)
{
    this.applicationKey = ko.observable(applicationKey);
    this.candidateLocation = ko.observable(location);
};


function ApplicationsVM(){

    var self = this;

    this.currentApplication = ko.observable("");

    this.setCurrentApplication = function(model){
        self.currentApplication(model);
    };


    this.applicationList = ko.observableArray([
        new application( 'key1', 'location1'),
        new application( 'key2', 'location3'),
        new application( 'key3', 'location4'),
        new application( 'key4', 'location5'),
        new application( 'key5', 'location6'),
        new application( 'key6', 'location7')
    ]);
};

var vm = new ApplicationsVM();
ko.applyBindings(vm);

然后在您的锚标签中使用click事件来设置当前应用程序:

<ul data-bind="foreach : applicationList">
    <li> <a href="#" data-bind="click : $root.setCurrentApplication" data-toggle="modal" data-target="#previewApplicantModal"> <span data-bind="text: applicationKey" ></span> </a> </li>
</ul>

最后在你的模态中你可以使用“with”绑定而不是点符号:

<div class="col-md-6" data-bind="with: currentApplication">
    <span data-bind="text: candidateLocation"></span>    
</div>