How to link new items using knockout?

How to link a new item after page loading?

I have something like this

system = function() { this.hello = function() { alert("hello"); } this.makeUI = function(container) { div = document.createElement("div"); div.innerHTML = "<button data-bind='click: hello'>Click</button>"; } } ko.applyBindings(new system); 

If I try this one

 this.makeUI = function(container) { div = document.createElement("div"); div.innerHTML = "<button data-bind='click: hello'>Click</button>"; ko.applyBindings(new system,div); } 

but according to these messages this will not work.

+6
source share
1 answer

The purpose of a knockout is to only knock out a single set of dom elements. Therefore, if you re-name applyBindings throughout the entire document, you will have problems with multiple bindings.

There are several cases where the call to applyBindings is justified several times, and this applies to partial views that were not in dom during the first binding and therefore were not bound. You can bind them by selectively looking at applyBindings on this dom element.

Here is an example of what you were trying to achieve. Your problem was that you did not embed the created node.

http://jsfiddle.net/madcapnmckay/qSqJv/

I would not recommend this approach for this particular example, there is a better way.

If you want to dynamically create dom elements and bind them to knockout, the most common approach is to use the built-in template functions, which take care of the insertion of the elements and bind any data binding attributes that it finds.

So, if you want to create some buttons that could do

 this.makeUI = function(container) { self.buttons.push({ text: "button " + self.buttons().length, handler: this.hello }); } 

Here is the fiddle.

http://jsfiddle.net/madcapnmckay/ACjvs/

Hope this helps.

+11
source

Source: https://habr.com/ru/post/912640/


All Articles