Adding observable properties to model after ko.applyBindings in knockout.js

佐手、 提交于 2020-02-23 13:04:43

问题


For example

function Model(){};
var model = new Model();
ko.applyBinding(model);

model.name = ko.observable('john');

I know the code will not work but is it possible to make it work ?


回答1:


I was able to accomplish this by using cleanNode and then reapplying the bindings.

function Model(){};
var model = new Model();
ko.applyBindings(model);

model.name = ko.observable('john');

var myDiv = $('#myDiv')[0];
ko.cleanNode(myDiv);
ko.applyBindings(model, myDiv);

<div id="myDiv">
    <span data-bind="text: name"></span>
</div>



回答2:


A possible solution would be binding to a partial view, for example:

<div id="viewOne">
  <input data-bind="value: name" />
</div>

<div id="viewTwo">
  <input data-bind="value: name" />
</div>

<script type="text/javascript">
  var viewModelA = {
     name: ko.observable("John")
  };

  var viewModelB = {
     name: ko.observable("Doe")
  };

  ko.applyBindings(viewModelA, document.getElementById("viewOne"));
  ko.applyBindings(viewModelB, document.getElementById("viewTwo"));
</script>

So in your case, after adding the new property, you can do apply bindings again only on the part of the view that requires the new data.




回答3:


You would probably need to call ko.applyBindings again. I'm not sure if it'll work though. If it doesn't, you probably would need to look into the KnockoutJS code to find out what applyBindings does and then figure ouit the functions you need to call to partially apply on your new binding.




回答4:


This is supposed to be able to get the applyBindings function to add just the one div. Currently trying it myself in my own application. Not too much luck so far though. Don't know how it would react in your application.

ko.applyBindings(model, document.getElementById('#yourdiv'));

Calling the applyBindings with just the model to bind it to creates additional bindings on the objects. This is not advised.

function Model(){};
var model = new Model();
model.name = ko.observable('john');
ko.applyBindings(model);

model.street = ko.observable('stationstreet');
ko.applyBindings(model);

The latter would create a single binding on the street object, however a second would be created on the name object.




回答5:


There is no need to call ko.applyBindings again. Most probably your binding code is called before your html code. If you move applyBinding to document ready everything will be ok!

For jquery:

$(function () {
    ko.applyBindings(viewModel);
});


来源:https://stackoverflow.com/questions/10270902/adding-observable-properties-to-model-after-ko-applybindings-in-knockout-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!