Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Knockout bind 2 links to different views and swich modelview

I'm new to knockout and want to have 2 links on the page with 2 models. I would like the click event on the links switch which view model gets displayed. I've tried a few ways and have a jfiddle https://jsfiddle.net/edgrttj3/7/ but I can't get it to work. Any idea on what I might be doing wrong?

<div id="content">

    <a id="button1" href="#" >View 1</a>&nbsp;
    <a id="button2" href="#" >View 2</a>&nbsp;
    <hr />

    <div data-bind="with: selectedView">
        <div data-bind="template: { name: templateName, data: data }"></div>
    </div>

    <script id="oneTmpl" type="text/html">
        <ul data-bind="foreach: items">
            <li>
                <span data-bind="text: id"></span>
                <input data-bind="value: name" />
            </li>
        </ul>
    </script>

    <script id="twoTmpl" type="text/html">
        First:
        <input data-bind="value: firstName" />
        Last:
        <input data-bind="value: lastName" />
    </script>
</div>

Here is the javascript:

var View = function (title, templateName, data) {
    this.title = title;
    this.templateName = templateName;
    this.data = data;
};

var subModelA = {
    items: ko.observableArray([
        { id: 1, name: "one" },
        { id: 2, name: "two" },
        { id: 3, name: "three" }
    ])
};

var subModelB = {
    firstName: ko.observable("Bob"),
    lastName: ko.observable("Smith")
};


var viewModel = {
    views: ko.observableArray([
        new View("one", "oneTmpl", subModelA),
        new View("two", "twoTmpl", subModelB)
    ]),
    selectedView: ko.observable()
};

function setSelectedView(newview) {
    alert(newview);
    if (newview == "oneTmpl") {
        viewModel.selectedView = viewModel.views[0];
    } else {
        viewModel.selectedView = viewModel.views[1];
    }
};
ko.applyBindings(viewModel);
        document.getElementById ("button1").addEventListener("click", setSelectedView('oneTmpl'), false);
        document.getElementById ("button1").addEventListener("click", setSelectedView('twoTmpl'), false);
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Actually your implementation is almost there. There are just couple of tweaks you need to do.

  • selectedView from the ViewModel is an observable object. An observable object is basically a function. In order to modify the value of that object you need to pass the new value as an argument selectedView(valueIsHere).
  • views from the ViewModel is an observable array object. The same like above, as an observable object is a function to get its value for a specific index you need to call it like a function first followed with its index views()[0]

So here is how it looks after the update:

var View = function (title, templateName, data) {
  this.title = title;
  this.templateName = templateName;
  this.data = data;
};

var subModelA = {
  items: ko.observableArray([
    { id: 1, name: "one" },
    { id: 2, name: "two" },
    { id: 3, name: "three" }
  ])
};

var subModelB = {
  firstName: ko.observable("Bob"),
  lastName: ko.observable("Smith")
};


var ViewModel =  function (){
  this.views = ko.observableArray([
    new View("one", "oneTmpl", subModelA),
    new View("two", "twoTmpl", subModelB)
  ]);
  this.selectedView = ko.observable();
  this.select = function(id){
    if (id === 1) {
        this.selectedView(this.views()[0]);
    } else {
        this.selectedView(this.views()[1]);
    }
  };
};

ko.applyBindings(new ViewModel());

And here are few changes to the button:

<a id="button1" href="#" data-bind="click: select(1)">View 1</a>&nbsp;
<a id="button2" href="#" data-bind="click: select(2)">View 2</a>&nbsp;
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda