jquery - How can I create a Knockout function that is used multiple times on the same page? -
i'm still learning knockout js
, i'm wondering how can create "general" view model /function can applied multiple elements on same page.
a concrete example i'm trying create global function slides down / html element adding css class. slide effect created using css transistion
.
so far it's working: (jsfiddle):
<button type="button" class="btn btn-primary" data-bind="click: slideinoutclick()"> show more details </button> <div class="slide-in-out-container w300" data-bind="css: { 'show200': slideout() === false }"> <div class="panel panel-primary"> <div class="panel-body"> <p>some text here</p> <p>and more text here</p> </div> </div> </div>
js:
// global knockout model ko.applybindings(new globalmodel()); function globalmodel(){ var self = this; self.slideout = ko.observable(); self.slideinoutclick = function(){ self.slideout(!self.slideout()); } }
the problem comes when need multiple sliding panels on same page. question is, how can use knockout achieve this?
you want extend knockout itself, creating custom binding handler. exact example mention in article, albeit jquery:
ko.bindinghandlers.slidevisible = { update: function(element, valueaccessor, allbindings) { // first latest data we're bound var value = valueaccessor(); // next, whether or not supplied model property observable, current value var valueunwrapped = ko.unwrap(value); // grab more data binding property var duration = allbindings.get('slideduration') || 400; // 400ms default duration unless otherwise specified // manipulate dom element if (valueunwrapped == true) $(element).slidedown(duration); // make element visible else $(element).slideup(duration); // make element invisible } };
for specific example either modify this, or, depending on how you're doing "css transition", may able using css
binding toggle class, , let css3 handle transition.
this allows keep view models (which close business logic) seperate view concerns such transitions.
Comments
Post a Comment