javascript - jQuery DOM manipulation from Knockout ViewModel - use bindingHandlers? -
i've got knockout viewmodel looks this:
function myviewmodel() { this.update = function() { ... } ... }
and bindinghandler looks this:
ko.bindinghandlers.mybindinghandler = { init: function(element, valueaccessor, allbindings, viewmodel) { function manipulatedom(element) { ... } } }
i want myviewmodel call manipulatedom whenever update method called.
i using callback set in bindinghandler:
function myviewmodel() { this.update = function() { ... this.mybindinghandlercallback(); } ... } ko.bindinghandlers.mybindinghandler = { init: function(element, valueaccessor, allbindings, viewmodel) { viewmodel.mybindinghandlercallback = manipulatedom.bind(null, element); } } <div data-bind="mybindinghandler: null"></div>
another idea had use 'updatecount' observable , subscribing in bindinghandler:
function myviewmodel() { this.updatecount = ko.observable(0); this.update = function() { ... this.updatecount(this.updatecount() + 1); } ... } ko.bindinghandlers.mybindinghandler = { update: function(element) { manipulatedom(element); } } <div data-bind="mybindinghandler: updatecount"></div>
both of these solutions feel fragile , messy. 'knockout' way of approaching sort of problem? should manipulating dom within viewmodel?
i should add manipulatedom function has lot of logic isn't applicable in knockout fashion (measuring window heights, measuring div heights etc...)
thanks!
second approach (with counter) better, because viewmodel shouldn't override , change viewmodel's behavior overriding properties.
instead of having counter, if update method changes other observable properties create computed property subscribe current state of viewmodel , automatically invoke dom manipulation binding if pass binding parameter, no need increment counter or other flag then.
Comments
Post a Comment