knockout.js - Unbinding jQuery event handlers when a KnockoutJs view is unloaded -
i have simple app 2 views, 1 "app" model , 2 view models. interested in working out how unbind jquery events.
the app view model has property:
var self = this; self.viewmodel = ko.observable(null);
the of import html snippets resides in master template , is:
<!-- ko if: viewmodel --> <div data-bind="template:{name:viewmodel().template, data:viewmodel(), afterrender: viewmodel().viewdidrender}"></div> <!-- /ko -->
in app model, after initialization, view model loaded. each view model has simple template property string refers html template render. info item in template declaration sets knockoutjs context current view model. afterrender binding ensures viewmodel's viewdidrender method called (with container html element parameter).
this means can following:
self.viewdidrender = function (parentelement) { self.containerelement = parentelement; $("html").on("click", function (event) { var elements = $(event.target).parents(); (var = 0; < elements.length; i++) if (elements[i] == self.containerelement[0] || elements[i] == self.containerelement) { alert("the target exists within parent element"); return; } self.open(false); }); };
there requirement intercept html elements click event. if event occurred target within parent element of subview ignore event, else set 'open' false (this part of lite dismiss mechanism see popovers in ios)
i finding when switch between 2 main views (the viewdidrender of illustration view invoked every time it's rendered), body click handler above bound multiple times.
i think javascript memory leak. whereabouts should 1 clean these bindings? can called $("html").off(...) etc... where? beforeremove event of template binding not invoke pure template item.... foreach bindings.
i could create method within of sub-view-models "viewwillhide", everytime new view pushed viewmodel property of app model, seek phone call viewwillhide method on view model. work. however, application more complex i'm demonstrating here. there hierarchy of view models , nested templates.
doing manually option; seem unusual there not opposite afterrender of template binding.
so do? manual approach? though cause cascade of changes throughout view model hierarchy in order propagate viewwillhide method downwards hierarchy top (app model) downwards smaller view models.
thanks
try using next code unbind jquery events
ko.utils.domnodedisposal.adddisposecallback(element, function() { //do cleanup });
edit: little fiddle demonstrate how wrap binding
http://jsfiddle.net/d6cjg/
problem adddisposecallback on div bounded template binding wont trigger callback because element never changes, elements within alter when template change.
here callback called http://jsfiddle.net/d6cjg/1/
knockout.js knockout-2.0
No comments:
Post a Comment