Where to write dom manipulation code when using knockout and MVVM

im starting to lower his head around the knockout, and if he correctly writes the code in view mode, which controls the animation of dom or lights, etc. As an example, I have this binding, which is passed to the div reference that I want to copy when the tr button is pressed.

<tr data-bind="click: function(data, event){$parent.Select('#PanelWrapper', $data)}"> 

In my view model, I have

 self.Select = function (panel, e) { console.log(ko.toJS(e)); if(self.SelectedEmployee() === e)return; self.$PanelWrapper = $(panel); var $Bottom = parseInt(self.$PanelWrapper.css("bottom")); if($Bottom === 0){ self.$PanelWrapper.animate({ bottom:"-95" }, 500, function(){ self.SelectedEmployee(e); self.Editable(new Employee(ko.toJS(e))); }).animate({ bottom:"0" }, 500); }else{ self.SelectedEmployee(e); self.Editable(new Employee(ko.toJS(e))); self.$PanelWrapper.animate({ bottom:"0" }, 500); } }; 

I am wondering if this is really true and that it follows the vmmv methodology. Any help would be appreciated

+4
source share
2 answers

No, it is not a good idea to manipulate the dom inside your viewmodel. The whole concept of MVVM is to separate the presentation from the data / user interface behavior.

You must use custom binding handlers , or you can also create these effects / controls (I don’t know what it is) outside of your view model. The view model should only model the view: data and commands for that data.

+7
source

You must change the dom directly when you encode a knockout.

I suggest using slideBinding (jQuery required).

I made a fiddle to demonstrate how to use it. This is a kind of master / detail view.

View:

 <div data-bind="foreach : people"> <div data-bind="click : $parent.onClick" style="cursor: pointer"> <span data-bind="text : name"></span> <div data-bind="slideVisible: $parent.selected() == $data"> <span data-bind="text : details"></span> </div> </div> </div> 

View Model:

 var vm = { selected: ko.observable(''), people : [{ name: "name1", details: "details1" }, { name: "name2", details: "details2" }], onClick: function (item) { vm.selected(item); } }; 

Hope this helps.

+2
source

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


All Articles